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
author's image
Abhijeet Pal Author and Editor in Chief @djangocentral

Abhijeet is a full-stack software developer from India with a strong focus on backend and system design. He is driven by the need to create impactful solutions that add value to the internet in any way possible.

LinkedIn Twitter Github

Latest Articles

Latest from djangocentral

Django 4.1 adds async-compatible interface to QuerySet

The much-awaited pull request for an async-compatible interface to Queryset just got merged into the main branch of Django.Pull Request - https://github.com/django/django/pull/14843 The Django core team has been progressively adding async suppor…
Read more →

3 min read

Making Django Admin Jazzy With django-jazzmin

Django admin is undoubtedly one of the most useful apps of Django. Over the years there has been very little change in the admin app as far as the UX is concerned and it's not a bad thing at all. Django admin was designed to provide a simple and minimali…
Read more →

4 min read