Reference library

Comprehensions & generators

List/dict/set comprehensions, generator expressions, and lazy iteration.

2 matches
Comprehensions & generators easy

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.

generators enumerate running-total
Python
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_to…
14 0 Open
Comprehensions & generators easy

How to Create a Line-Numbered Generator with enumerate start in Python

This Python code defines a generator that yields lines prefixed with their index, using enumerate's start parameter to offset numbering.

enumerate generator yield
Python
def line_numbered_lines(lines, start=1):
    for idx, line in enumerate(lines, start):
        yield f"{idx:3} {line}"


if __name__ == "__main__":
    sample = ["first line", "second", "third"]
    for numbered in line_numbered_lines(sample, start=10):
        print(numbered)
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Comprehensions & generators — Python code examples

What you will find here

This page collects comprehensions & generators snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.