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.
Python code
11 linesdef 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
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
- Use `itertools.accumulate` to compute the running total as a list, then zip with `enumerate`
- 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
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.