Tutorials / Python: Intermediate to Advanced / Iterators and generators

Iterators and generators

14 min read python
Course contents (15 lessons)
  1. Iteration the Python way
  2. List, dict and set comprehensions
  3. Iterators and generators
  4. Functions as building blocks
  5. Closures and decorators
  6. Context managers and the with statement
  7. Object-oriented Python in depth
  8. Classes and dataclasses
  9. Properties and special (dunder) methods
  10. Inheritance versus composition
  11. Quality: types, packaging and tests
  12. Type hints and mypy
  13. Packaging a project with pyproject.toml
  14. Testing with pytest
  15. Async code and web APIs
  16. async and await with asyncio
  17. Working with HTTP APIs and JSON
  18. Performance, concurrency and a final project
  19. Performance and profiling
  20. Concurrency: threads versus processes
  21. Final project: a price tracker command-line tool

What a for loop really does

When you write for x in something, Python calls iter(something) to get an iterator. Then it calls next() on that iterator again and again until it raises StopIteration. That is the whole protocol. Lists, strings, dictionaries, files and range objects are all iterable, meaning iter() works on them.

it = iter([10, 20])
print(next(it))    # 10
print(next(it))    # 20
print(next(it))    # raises StopIteration

An iterator remembers where it is. Once exhausted, it stays exhausted. This is the source of a very common bug: iterating over the same iterator twice and finding the second pass empty.

Writing an iterator the hard way

You could write a class with __iter__ and __next__. It works, but it is a lot of code for a simple idea. Generators do the same job in a few lines.

Generator functions

A function that contains yield is a generator function. Calling it does not run the body. It returns a generator object. Each time a value is requested, the function runs until the next yield, hands that value over, and pauses with all its local variables intact.

def countdown(start):
    print("starting")
    while start > 0:
        yield start
        start -= 1
    print("finished")


gen = countdown(3)
print("created, nothing printed yet")
print(next(gen))
print(next(gen))
print(list(gen))

Output:

created, nothing printed yet
starting
3
2
finished
[1]

Trace it carefully. Creating the generator prints nothing. The first next() runs the body up to the first yield, so "starting" appears and 3 is returned. The second next() resumes after the yield, decrements, and yields 2. Then list(gen) resumes again: it yields 1, the loop ends, "finished" is printed, and the list [1] is printed last. Tracing generator output in your head like this is the skill you need. Always ask: when does the body actually run? The answer is only when a value is requested.

Lazy pipelines

Generators shine when you chain them. Imagine a 4 GB log file. Reading it all into a list would use 4 GB of memory. With generators, only one line exists at a time.

def read_lines(path):
    with open(path, encoding="utf-8") as f:
        for line in f:
            yield line.rstrip("\n")


def only_errors(lines):
    for line in lines:
        if " ERROR " in line:
            yield line


def first_n(items, n):
    for i, item in enumerate(items):
        if i >= n:
            return
        yield item


errors = first_n(only_errors(read_lines("app.log")), 5)
for line in errors:
    print(line)

Nothing is read until the final for loop asks for a line. Then the request travels back through the chain, and each stage does a little work. Because first_n stops after five items, the file reader stops too. We never read the rest of the file. The file is also closed properly, because the with block exits when the generator is closed or garbage collected.

yield from

To pass all values of another iterable through, use yield from:

def walk(tree):
    """Yield every value in a nested dict of dicts."""
    for key, value in tree.items():
        if isinstance(value, dict):
            yield from walk(value)
        else:
            yield value

The itertools module

The standard library has ready-made iterator tools in itertools. These save you from rewriting common generators:

  • itertools.islice(it, 5) takes the first five items (our first_n).
  • itertools.chain(a, b) goes through a and then b.
  • itertools.batched(items, 3) (Python 3.12 and later) groups items into tuples of three.
  • itertools.groupby(sorted_items, key) groups neighbouring items with the same key.

Infinite generators

A generator does not need to end. This one gives an endless stream of invoice numbers, and the caller decides when to stop.

def invoice_numbers(prefix="INV", start=1):
    n = start
    while True:
        yield f"{prefix}-{n:05d}"
        n += 1

numbers = invoice_numbers()
print(next(numbers))    # INV-00001
print(next(numbers))    # INV-00002

Common mistakes

  • Using a generator twice. After list(gen), calling list(gen) again gives []. Make a new generator or store the list.
  • Calling len() on a generator. It has no length, since the values do not exist yet. Count by iterating.
  • Expecting errors early. Exceptions inside the body appear only when the values are consumed, which can be far from the line that created the generator.
  • Returning a generator when callers need a list. Laziness is not always the right choice. For small data, a list is simpler and lets callers index and reuse it.

Try it yourself

Write a generator fibonacci() that yields the Fibonacci numbers forever. Use itertools.islice to print the first ten. Then write read_csv_rows(path) as a generator that yields dictionaries using csv.DictReader, and a second generator that filters the rows. Connect them in a pipeline and check that memory use stays flat on a large file.

python
def countdown(start):
    print("starting")
    while start > 0:
        yield start
        start -= 1
    print("finished")


gen = countdown(3)
print("created, nothing printed yet")
print(next(gen))
print(next(gen))
print(list(gen))

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account