Find sum of list elements in python
A python list is a collection of elements of same or different data types.
Suppose you have a list of numbers and you want to find the sum of all elements of the list.
This article shall detail out different ways in which this can be done.
Method 1: Iterating over list using for loop
This method is based on the below algorithm.
1. Initialize a variable to hold the sum of element.
2. Iterate over the list using a for loop and retrieve each element of the list.
3. Add this element to the variable initialized above
4. After the list iteration is complete, the variable of Step 1 will hold the sum of list elements.
Python program written as per above algorithm follows
# initialize a list of integers num_list = [1, 5, 4, 45, 12] # initialize variable to hold the sum of list elements total = 0 # iterate over the list for num in num_list: # add current list element to the sum total = total + num print("Sum of elements of list is", total)
It produces the following output
Sum of elements of list is 67
Method 2: Iterating over list using while loop
This method is same as the previous method but it uses a while
loop instead of for
loop.
Algorithm for this method would comprise of following steps
1. Initialize a variable to hold the sum of list elements.
2. Initialize a variable to hold loop index.
3. Initialize a variable to hold the number of list elements.
This variable and the variable from previous step will be used to iterate over the list
4. Iterate over the list using a while
loop till the value of variable of step 2 is less than the value of variable of step 3.
5. In every loop iteration, add the element at current loop index(value of variable in step 2) to the total(variable of step 1).
6. Increment loop index by 1.
7. After the loop completes, variable in step 1 will be holding the sum of list elements.
Code written as per the above algorithm is as follows.
# initialize a list of integers num_list = [1, 5, 4, 45, 12] # initialize variable to hold the sum of list elements total = 0 # number of elements in list list_size = len(num_list) # variable to keep track of loop loop_counter = 0 # iterate over the list while loop_counter < list_size: # add current list element to the sum total = total + num_list[loop_counter] # increment loop index loop_counter = loop_counter + 1 print("Sum of elements of list is", total)
Output of above program is
Sum of elements of list is 67
Method 3: Using sum() function
Python provides a built-in function sum
which takes an object which can be iterated upon(such as a list) and returns the sum of the values contained in this object.
Python docs for sum function state
Return the sum of a ‘start’ value (default: 0) plus an iterable of numbers
Program showing the usage of this function is shown below
# initialize a list of integers num_list = [1, 5, 4, 45, 12] # add list elements using sum function total = sum(num_list) print("Sum of list elements is",total)
Output of above program is
Sum of list elements is 67
Method 4: Using recursive approach 1
A recursive method is one which keeps on calling itself till some condition is met.
It may or may not return a result.
It is also necessary to write a condition in recursive method which causes it to return otherwise it will keep on calling itself infinitely.
Below code shows an example of a recursive method.
# initialize a list of integers num_list = [1, 5, 4, 45, 12] # recursive method to calculate the sum of list elements def recursive(num_list, list_size): # check if list is empty, return 0 if list_size == 0: return 0 # add last element with other list elements return num_list[list_size-1] + recursive(num_list, list_size - 1) total = recursive(num_list, len(num_list)) print("Sum of list elements is", total)
Above code defines a recursive method to calculate the sum of list items. It takes 2 arguments, the list whose elements need to be added and the size of list.
Method retrieves the last element of the list by subtracting 1 from the size of list and calls itself again with list size reduced by 1.
In every call, it adds the last list element with the result of its recursive call.
This way, with each recursive call list elements are added(starting from last element to first element) and list size is reduced by 1.
When list size reaches 0 the last recursive call terminates by returning 0 and method returns the sum of list elements.
Output is
Sum of list elements is 67
Method 5: Using recursive approach 2
This method is another recursive alternative to calculating the sum of list elements.
This method takes only one argument which is the list whose elements are to be added.
In every invocation, it returns the sum of first element and the result of its recursive call with the first element removed from the list.
Thus, in every call, the size(or length) of the list received as argument is reduced by 1
In every call, this method checks for the length of the list.
When the length reaches 1, it returns the first element. Thus, with each recursive call list elements are added(starting from first element till last element).
For removing first element, it uses slicing operator(:
).
Expression num_list[1:]
means all list elements starting from element at index 1(second element) since index of elements in a list starts from 0.
Code example follows.
# initialize a list of integers num_list = [1, 5, 4, 45, 12] def recursive(num_list): # check if there is only 1 element in the list, return it if len(num_list) == 1: return num_list[0] # add first element with other list elements return num_list[0] + recursive(num_list[1:]) total = recursive(num_list) print("Sum of list elements is", total)
Output of above code is
Sum of list elements is 67
This post lists out various methods that can be utilized to calculate sum of list elements in python.
Hope it helped you out in learning them.
Method 1, line 9, sum should be replaced with the variable “total”.
Yes.. that’s right.
Corrected, thanks !!