Program to find the sum of elements of lists using Python

Introduction

In this section of python programming, we will understand the different ways to calculate the sum of elements in the list.

Python provides in-built function sum() which we have earlier used in array also. Here we will also focus on other ways through which we can obtain the sum of elements of the list.

Program

```sum_res, sum_res1, j = 0, 0, 0

list = [1, 2, 3, 1, 5, 6, 2, 3, 1]

# Using recursion

def sum_list(list, n):

if (n == 0):

return 0

else:

return list[n - 1] + sum_list(list, n - 1)

sum_recursion = sum_list(list, len(list))

print("Sum using recursion: ",sum_recursion)

# Using for loop

for i in range(0, len(list)):

sum_res = sum_res + list[i]

print("Sum using for loop: ",sum_res)

#Using sum()

result = sum(list)

print("Sum using sum(): ", result)

# Using while loop

while(j < len(list)):

sum_res1 = sum_res1 + list[j]

j = j + 1

print("Sum using while loop: ",sum_res1)```

Explanation

In the above python code, we have used four methods to obtain the sum of elements in the list; recursion, for loop, while loop and sum(). We can see that in for and while loop, each time the index is increased the value placed at that index is added in the sum_* variable. Whereas in recursion, we are recursively calling the function sum_list() and value is returned when n = 1.

The simplest and easiest way to calculate the sum is by using python in-built function sum(). It directly sums all the elements in the list and return the result.

Author

• A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.