We’ll see different ways to find sum of elements in a list. The requirement is that if a list contains numbers, then find the sum of all the elements in the list.
Input: [3, 10, 15, 35, 55]
Output: 118
We’ll discuss four ways to find the sum of all the elements in the list:
- Using
sum()
method - Using for loop
- Using while loop
- Using recursive method
Method 1: Using sum() method
We can pass list as an argument to the sum() method. This is easiest way to find the sum of elements of a list.
# Python program to find sum of elements in list using sum() # create list listOfNumbers = [3, 10, 15, 35, 55] # calculate sum using sum() method sum = sum(listOfNumbers) print("sum of elements:",sum)
Output
sum of elements: 118
Method 2: Using for loop
In this method, we’ll initialize sum to zero. We then iterate the elements of the list using for loop and add each element to the sum.
# Python program to find sum of elements in list using for loop sum = 0 # create list listOfNumbers = [3, 10, 15, 35, 55] for element in listOfNumbers: sum = sum + element print('sum of elements:',sum)
Output
sum of elements: 118
Method 3: Using while loop
In this method, we’ll initialize sum to zero. We then iterate the elements of the list using for while loop based on index of elements and add each element to the sum.
# Python program to find sum of elements in list using while sum = 0 index = 0 # create list listOfNumbers = [3, 10, 15, 35, 55] # Iterate elements of list based on index # and add every element to sum while(index < len(listOfNumbers)): sum = sum + listOfNumbers[index] index += 1 print('sum of elements:',sum)
Output
sum of elements: 118
Method 4: Using recursive method
In this method, we’ll use recursive method to calculate the sum of elements of a list.
# Python program to find sum of all # elements in list using recursion # creating a list listOfNumbers = [3, 10, 15, 35, 55] # recursive function to find sum of elements def sumOfElements(list, size): if (size == 0): return 0 else: return list[size - 1] + sumOfElements(list, size - 1) # Driver code total = sumOfElements(listOfNumbers, len(listOfNumbers)) print("Sum of elements: ", total)
Output
sum of elements: 118