How to Calculate the Sum of List Elements in Python
Iterates over a list with a for loop, accumulates each number into a total variable, and returns the sum of all elements.
Python code
11 linesdef sum_list_elements(numbers):
"""Return the sum of all elements in a list."""
total = 0
for num in numbers:
total += num
return total
if __name__ == "__main__":
sample_list = [1, 2, 3, 4, 5]
result = sum_list_elements(sample_list)
print(f"The sum of {sample_list} is {result}")
Output
The sum of [1, 2, 3, 4, 5] is 15
How it works
The function initializes total to 0 and then loops through each num in the list, adding it to total with += (shorthand for total = total + num). This works for any iterable, not just lists, and handles numeric types like integers and floats. After the loop, the accumulated value is returned. The if __name__ == "__main__" guard ensures the demo only runs when the script is executed directly, not when imported.
Common mistakes
- Forgetting to initialize `total` to 0 before the loop, causing a NameError.
- Using `total + num` without reassigning it, so the sum never updates.
- Assuming non-numeric elements will work; strings cause a TypeError.
- Not returning the total but printing inside the function, reducing reusability.
Variations
- Use the built-in `sum()` function: `sum(numbers)` for a concise one-liner.
- Use `functools.reduce` with `operator.add` for a functional style.
Real-world use cases
- Calculating the total revenue from a list of order amounts in an e-commerce application.
- Summing user scores from a leaderboard list to compute average performance.
- Aggregating sensor readings to get total energy consumption over time.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.