Python program to find sum of elements in list

• Difficulty Level : Easy
• Last Updated : 09 Aug, 2022

Given a list of numbers, write a Python program to find the sum of all the elements in the list.
Example:

Input: [12, 15, 3, 10]
Output: 40

Input: [17, 5, 3, 5]
Output: 30

Example #1:

Python3

 # Python program to find sum of elements in listtotal = 0 # creating a listlist1 = [11, 5, 17, 18, 23] # Iterate each element in list# and add them in variable totalfor ele in range(0, len(list1)):    total = total + list1[ele] # printing total valueprint("Sum of all elements in given list: ", total)

Output:

Sum of all elements in given list:  74

Example #2 : Using while() loop

Python3

 # Python program to find sum of elements in listtotal = 0ele = 0 # creating a listlist1 = [11, 5, 17, 18, 23] # Iterate each element in list# and add them in variable totalwhile(ele < len(list1)):    total = total + list1[ele]    ele += 1     # printing total valueprint("Sum of all elements in given list: ", total)

Output:

Sum of all elements in given list:  74

Example #3: Recursive way

Python3

 # Python program to find sum of all# elements in list using recursion # creating a listlist1 = [11, 5, 17, 18, 23] # creating sum_list functiondef sumOfList(list, size):   if (size == 0):     return 0   else:     return list[size - 1] + sumOfList(list, size - 1)  # Driver code    total = sumOfList(list1, len(list1)) print("Sum of all elements in given list: ", total)

Output:

Sum of all elements in given list:  74

Example #4: Using sum() method

Python3

 # Python program to find sum of elements in list # creating a listlist1 = [11, 5, 17, 18, 23] # using sum() functiontotal = sum(list1) # printing total valueprint("Sum of all elements in given list: ", total)

Output:

Sum of all elements in given list:  74

Example 5: Using add() function of operator module.

First we have to import the operator module then using the add() function of operator module adding the all values in the list.

Python3

 # Python 3 program to find the sum of all elements in the# list using add function of operator module from operator import*list1 = [12, 15, 3, 10]result = 0for i in list1:  # Adding elements in the list using  # add function of operator module    result = add(i, 0)+result# printing the resultprint(result)

Output

40

Python3

 list1 = [12, 15, 3, 10];s=0for i,a in enumerate(list1):  s+=aprint(s)

Output

40

My Personal Notes arrow_drop_up