appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Iterators and generators

Lesson 1 of 512 minAdvanced

Produce values one at a time, so large or infinite data costs almost no memory.

A for loop works on any iterable. Under the hood Python asks the object for an iterator and calls next() until StopIteration.

Generator functions

A function that uses yield becomes a generator. It returns a value, pauses with its state intact and resumes on the next request.

def read_errors(path):
    with open(path, encoding="utf-8") as f:
        for line in f:
            if "ERROR" in line:
                yield line.rstrip()

for line in read_errors("app.log"):
    print(line)

Nothing runs until you iterate. The file is read lazily, one line at a time, however big it is.

Generator expressions

squares = (n * n for n in range(1_000_000))   # no list is built
print(sum(squares))
print(sum(n * n for n in range(10)))
  • Use [ ... ] (a list) when you need the values several times or need len().
  • Use ( ... ) (a generator) when you consume them once, in order.
  • A generator can only be used once. After it is exhausted, it yields nothing.

itertools

from itertools import islice, chain, groupby
first_ten = list(islice(read_errors("app.log"), 10))

Noteyield from other() delegates to another generator, and the standard library itertools has many building blocks for pipelines.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What is the main benefit of a generator?
2. What happens if you iterate a generator a second time after finishing it?
3. Which keyword turns a function into a generator?

Key terms