Python Program To Find The Sum Of Elements Of An Array or List

1 min read

Problem Definition

Make a Python Function which takes an array or list as input and returns the sum of its elements, for example  array[ 1, 2, 3, 4] will return 1 + 2 + 3 + 4 = 10

Solution

In this article, we will go through two different methods of tackling the same problem.

Method 1: Using loop

In this method first, we are creating a variable total to store the sum and initializing it to 0. Next, the for loop iterates over each element of the array / list and storing their sum in the total variable, at last function returns the total.

def array_summer(arr):
    total = 0
    for item in arr:
        # shorthand of total = total + item
        total += item
    return total

#  Test input
print(array_summer([1, 2, 3, 3, 7]))

Output:

16

Method 2: Using Python's built-in function sum() [ Recommended ]

Python comes with an in-built solution for adding items of iterable (list, tuple, dictionary), the sum() method simply returns the sum of each item of the gives list or array.

def array_summer(arr):
    return sum(arr)

#  Test input
print(array_summer([1, 2, 3, 3, 7]))

Output:

16

we went through two different methods of summing the elements of an array however using sum() function made our code more compact and faster, for a very large list sum() is more efficient therefore it's the recommended way.


PROGRAMS

Latest Articles

Latest from djangocentral

Capturing Query Parameters of request.get in Django

In Django, the request object contains a variety of information about the current HTTP request, including the query parameters. Query parameters are a way to pass additional information in the URL and are used to filter or sort data. The request object p…
Read more →

2 min read

Understanding related_name in Django Models

In Django, related_name is an attribute that can be used to specify the name of the reverse relation from the related model back to the model that defines the relation. It is used to specify the name of the attribute that will be used to access the relat…
Read more →

2 min read