How to Calculate a Cumulative Sum in Python

Build a new list where each element equals the running total of all numbers up to that index in the original list.

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

Python code

9 lines
Python 3.9+
numbers = [1, 2, 3, 4, 5]
cumulative_sum = []
running_total = 0

for num in numbers:
    running_total += num
    cumulative_sum.append(running_total)

print(cumulative_sum)

Output

stdout
[1, 3, 6, 10, 15]

How it works

The loop starts with running_total = 0 and adds each number to it as it iterates. After updating the total, that value is appended to the output list, so each position reflects the sum of everything seen so far. This approach is straightforward and works with any iterable of numbers, not just lists.

Common mistakes

  • Forgetting to reset the running total before the loop, causing the result to include prior data.
  • Attempting to use `sum()` slice inside the loop (e.g., `sum(numbers[:i])`) which is O(n²) for large lists.
  • Mutating the original list while iterating over it, which can cause skipped elements.

Variations

  1. Use `itertools.accumulate` for a concise, efficient one-liner: `from itertools import accumulate; list(accumulate(numbers))`.
  2. Use a list comprehension with a variable updated externally if you prefer functional-style code.

Real-world use cases

  • Tracking cumulative sales or revenue totals on a dashboard report.
  • Computing the prefix sum of an array for fast range-sum queries in algorithm problems.
  • Accumulating a running total of expenses to monitor budget depletion 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.