Enumerate a Generator With a Running Total in Python

A generator that yields each element with its index and a cumulative sum, letting you track a running total as you iterate.

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

Python code

11 lines
Python 3.9+
def running_total_enum(iterable):
    """Yields (index, item, running_total) for each element."""
    total = 0
    for index, item in enumerate(iterable):
        total += item
        yield index, item, total

if __name__ == "__main__":
    numbers = [10, 20, 30, 40, 50]
    for idx, value, running_sum in running_total_enum(numbers):
        print(f"Index {idx}: value={value}, running_total={running_sum}")

Output

stdout
Index 0: value=10, running_total=10
Index 1: value=20, running_total=30
Index 2: value=30, running_total=60
Index 3: value=40, running_total=100
Index 4: value=50, running_total=150

How it works

The running_total_enum function is a generator because it uses yield, so it produces values on demand rather than building a list. Each iteration adds the current item to total and then yields the index, value, and updated total as a tuple. The enumerate built-in provides the index automatically, while the loop logic maintains the cumulative sum. This is a lazy, memory-efficient pattern that works on any iterable, including infinite streams, since only one item is processed at a time.

Common mistakes

  • Forgetting to reset the total at the start of the generator, causing stale sums across calls
  • Using `return` instead of `yield`, which stops the generator after the first item
  • Assuming the input iterable is always finite, ignoring infinite iterables
  • Mutating the original iterable while iterating, which can corrupt totals

Variations

  1. Use `itertools.accumulate` to compute the running total as a list, then zip with `enumerate`
  2. Create a class-based iterator with `__iter__` and `__next__` for reusable state

Real-world use cases

  • Processing log entries and tracking cumulative counts or byte sizes per event.
  • Streaming financial transactions to compute a live account balance as items arrive.
  • Batch-processing sensor data while maintaining a rolling sum for pattern detection.

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.