Find sum of elements in List - Python
Finding the sum of elements in a list means adding all the values together to get a single total. For example, given a list like [10, 20, 30, 40, 50], you might want to calculate the total sum, which is 150. Let's explore these different methods to do this efficiently.
Using sum()
sum() function is the most efficient way to calculate the sum of all elements in a list. It automatically takes care of iterating over the list and summing up the values for you.
a = [10, 20, 30, 40, 50]
res = sum(a)
print(res)
Output
150
Explanation: sum() function adds all the numbers in the list a and stores the result in res.
Using for loop
For loop gives you more control over the process. By manually iterating over the list, you can accumulate the sum step by step.
a = [10, 20, 30, 40, 50]
res = 0 # Initialize sum variable
for i in a:
res += i
print(res)
Output
150
Explanation: For loop iterates through each element in the list, adding it to res in each step until all elements are summed.
Using list comprehension
List comprehension allows you to create a new list based on an existing one and then use sum() to calculate the total. This is a more Pythonic way to do things when you want to transform the list first.
a = [10, 20, 30, 40, 50]
res = sum([i for i in a])
print(res)
Output
150
Explanation: List comprehension creates a new list identical to a and the sum() function then calculates the total of its elements, storing the result in res.
Using reduce()
reduce() function from the functools module applies a function (in this case, addition) to the elements of the list cumulatively. This method is less commonly used but provides a functional programming style solution.
from functools import reduce
a = [10, 20, 30, 40, 50]
res = reduce(lambda x, y: x + y, a)
print(res)
Output
150
Explanation: reduce() function uses the lambda to cumulatively add pairs of elements from left to right, resulting in the total sum stored in res.