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.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

11 lines
Python 3.9+
def 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

stdout
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

  1. Use the built-in `sum()` function: `sum(numbers)` for a concise one-liner.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.