0
0
PythonHow-ToBeginner · 3 min read

How to Find Cumulative Sum of List in Python Easily

To find the cumulative sum of a list in Python, you can use itertools.accumulate() which returns running totals. Alternatively, you can use a simple loop to add each element to a running total and store the results in a new list.
📐

Syntax

The main way to get a cumulative sum is using itertools.accumulate(iterable). It takes an iterable like a list and returns an iterator with running sums.

Alternatively, you can use a loop to add each element to a total and append it to a new list.

python
from itertools import accumulate

cumulative_sums = list(accumulate([1, 2, 3, 4]))
💻

Example

This example shows how to use itertools.accumulate and a manual loop to find the cumulative sum of a list.

python
from itertools import accumulate

numbers = [1, 2, 3, 4, 5]

# Using itertools.accumulate
cumulative1 = list(accumulate(numbers))
print("Cumulative sum with accumulate:", cumulative1)

# Using a manual loop
cumulative2 = []
running_total = 0
for num in numbers:
    running_total += num
    cumulative2.append(running_total)
print("Cumulative sum with loop:", cumulative2)
Output
Cumulative sum with accumulate: [1, 3, 6, 10, 15] Cumulative sum with loop: [1, 3, 6, 10, 15]
⚠️

Common Pitfalls

One common mistake is trying to modify the original list instead of creating a new one, which can cause unexpected bugs.

Another is forgetting to convert the accumulate iterator to a list before printing or using it.

python
numbers = [1, 2, 3]

# Wrong: modifying original list in place (not recommended)
for i in range(1, len(numbers)):
    numbers[i] += numbers[i-1]
print(numbers)  # This changes the original list

# Right: create a new list instead
from itertools import accumulate
cumulative = list(accumulate([1, 2, 3]))
print(cumulative)
Output
[1, 3, 6] [1, 3, 6]
📊

Quick Reference

Here is a quick summary of methods to find cumulative sums in Python:

MethodDescriptionExample
itertools.accumulateReturns running totals as an iteratorlist(accumulate([1,2,3])) -> [1,3,6]
Manual loopAdd elements one by one to a running totalUse a for loop and append sums to a new list
NumPy cumsumFor numeric arrays, returns cumulative sumsnp.cumsum([1,2,3]) -> array([1,3,6])

Key Takeaways

Use itertools.accumulate to get cumulative sums easily and efficiently.
Convert the accumulate iterator to a list to use or print the results.
Manual loops work well for beginners and give clear control over the process.
Avoid modifying the original list to prevent bugs.
For numeric data, NumPy's cumsum is a fast alternative.