Find Sum of all Elements in Python List | Using Recursion, Reduce
Python list is one of the very useful data types in Python. Python list is nothing but an array of elements. As we are interested to calculate the sum of the elements, we are considering all the elements in the list as numbers.
Problem Statement: Write a Python program to find the sum of all elements in the List.
1. Using sum()
We can calculate the sum of all the elements in the Python list, using a simple building function sum().
If you know the sum() function. This is a very simple and one-liner solution.
2. Using recursion
Many times, in interviews, you will ask to write your own Python program to calculate the sum of all the elements using recursion. You can not use any built-in function.
myList=[23,4,2,6,7] def sumOfList(myList, nSum): if len(myList): return sumOfList(myList[1:], nSum+myList) else: return nSum print(sumOfList(myList, 0))
The code is self-explanatory. The only thing is that you should have a good understanding of how recursion work.
This problem was asked in McAfee coding round.
3. Using for loop
You can also solve it using for loop.
myList=[23,4,2,6,7] def sumOfList(myList): nSum=0 for i in myList: nSum+=i return nSum print(sumOfList(myList))
4. Using lambda and reduce function
To use the reduce method you have to import
functools module in your Python program.
Lambda is a special anonymous function. You can read more about the lambda function in Python.
import functools myList=[23,4,2,6,7] print(functools.reduce(lambda a, b: a+b, myList))
This program has more complexity. As we are traversing each element and calling recursive function, it takes time O(n). As we are using recursion here, it requires extra memory to save the output from previous recursive calls.
This is a simple tutorial with a Python program to find the sum of all elements in the list. If you are beginners, I would recommend solving coding interview questions for practicing.
Leave a Reply