Trusted answers to developer questions

Educative Answers Team

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

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

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 return total my_list = [1,3,5,2,4] print "The sum of my_list is", sum_of_list(my_list)

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)

`sum()`

methodThis 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

Copyright ©2022 Educative, Inc. All rights reserved

RELATED COURSES

View all Courses

Keep Exploring

Related Courses