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.
Python code
9 linesnumbers = [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
[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
- Use `itertools.accumulate` for a concise, efficient one-liner: `from itertools import accumulate; list(accumulate(numbers))`.
- 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
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.