Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

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

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

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read