How to Accumulate Values with a Generator in Python
This generator yields the running total of an iterable's elements, producing a cumulative sum with each step.
Python code
13 linesdef accum(iterable):
total = 0
for item in iterable:
total += item
yield total
# Demo
if __name__ == "__main__":
data = [1, 2, 3, 4, 5]
print(list(accum(data))) # [1, 3, 6, 10, 15]
# Also works with any iterable, e.g., range
print(list(accum(range(1, 6)))) # [1, 3, 6, 10, 15]
Output
[1, 3, 6, 10, 15]
[1, 3, 6, 10, 15]
How it works
The accum generator maintains a running total and yields it after each addition, so each next() call returns the cumulative sum up to that point. Because it uses yield instead of return, the function becomes a generator, allowing lazy evaluation over large or infinite streams. The loop over iterable can handle any iterable, including lists, tuples, and ranges. Converting to a list materializes all values at once, but you can also iterate directly to process each running total as it's produced.
Common mistakes
- Forgetting that generators are single-use; you cannot iterate twice over the same generator object.
- Using `return total` inside the generator, which would stop iteration early.
- Assuming the input must be a list; any iterable works, but it must produce numeric values.
- Modifying the input list during iteration, which can cause unexpected results.
Variations
- Use `itertools.accumulate` from the standard library for a built-in equivalent.
- Use a list comprehension with a loop to build the cumulative list directly.
Real-world use cases
- Computing a running total of daily sales as part of a reporting script.
- Tracking cumulative progress counts while processing large log files streamingly.
- Generating prefixes (cumulative sums) of a time series for cumulative statistics.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.