Python program to find sum of elements in list
In this article, we will explore various method to find sum of elements in list. The simplest and quickest way to do this is by using the sum() function.
Using sum()
The sum() function is a built-in method to sum all elements in a list.
a = [10, 20, 30, 40]
res = sum(a)
print(res)
Output
100
Explanation: The sum() function takes an iterable as its argument and returns the sum of its elements.
Using a Loop
To calculate the sum without using any built-in method, we can use a loop (for loop).
a = [10, 20, 30, 40]
# Initialize a variable to hold the sum
res = 0
# Loop through each value in the list
for val in a:
# Add the current value to the sum
res += val
print(res)
Output
100
Frequently Asked Question on Finding Sum of Elements in List
What is sum() function in Python?
The sum() function is a built-in Python function that takes an iterable (such as a list) and returns the sum of its elements.
Can I use sum() function for non-numeric elements?
No, sum() function works with numeric data types. If you try to use it with non-numeric elements, you will get a TypeError.
Can I sum elements in a nested list?
To sum elements in a nested list, you need to flatten the list before applying the sum() function. This can be done using loops or using itertools.chain(), which help to store all elements into a single list.
What happens if my list is empty?
If your list is empty, using sum() function will return 0 by default. This is because there are no elements to add and the default return value of the function is 0.