Related Tags

sum
list
python

# How to compute the sum of a list in python Educative Answers Team

When given a list of integers, how do you find the sum of all the elements in the list? ## Algorithms

Let’s have a look at a few of the algorithms used to compute the sum of a list in Python.

### 1. Using a simple loop

The most basic solution is to traverse the list using a for/while loop, adding each value to the variable total. This variable ​will hold the sum of the list at the end of the loop. See the code below:

def sum_of_list(l):
total = 0
for val in l:
total = total + val

my_list = [1,3,5,2,4]
print "The sum of my_list is", sum_of_list(my_list)

### 2. Computing the sum recursively

In this approach, instead of using loops, we will calculate the sum recursively. Once the end of the list is reached, the function will start to roll back. SumOfList takes two arguments as parameters: the list and the index of the list (n). Initially, n is set at the maximum possible index in the list and decremented at each recursive call. See the code below:

def sum_of_list(l,n):
if n == 0:
return l[n];
return l[n] + sum_of_list(l,n-1)

my_list = [1,3,5,2,4]
print "The sum of my_list is", sum_of_list(my_list,len(my_list)-1)

### 3. Using the sum() method

This is the simplest approach. Python has the built-in function sum() to compute the sum of the list. See the code below:

my_list = [1,3,5,2,4]
print "The sum of my_list is", sum(my_list)

RELATED TAGS

sum
list
python 