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.
Table of Contents
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.
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.
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))
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.