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.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 14 views 0 copies

Python code

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

stdout
[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

  1. Use `itertools.accumulate` from the standard library for a built-in equivalent.
  2. 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

Run this sample

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

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.