Iterators and generators · 4 / 15 Theory

Generator pipelines

One of the best ideas with generators is chaining them: the output of one is the input of the next, like a pipeline. Each value goes through all the stages before the next one is processed.

A step-by-step example

def evens(numbers):
    for n in numbers:
        if n % 2 == 0:
            yield n

def squares(numbers):
    for n in numbers:
        yield n * n

data = [1, 2, 3, 4, 5, 6]

result = squares(evens(data))

print(list(result))   # [4, 16, 36]

Each stage does one thing and is easy to read and to test separately. No intermediate list is created: the value 2 goes through evens and squares before 3 is even looked at.

Seeing the order of execution

With a few print calls you can see how they work at the same time:

def evens(numbers):
    for n in numbers:
        print("evens looks at", n)
        if n % 2 == 0:
            yield n

def squares(numbers):
    for n in numbers:
        print("squares receives", n)
        yield n * n

for value in squares(evens([1, 2, 3, 4])):
    print("result", value)
# evens looks at 1
# evens looks at 2
# squares receives 2
# result 4
# evens looks at 3
# evens looks at 4
# squares receives 4
# result 16

Practice with Generator pipeline.

The same pipeline with generator expressions

For simple operations it is enough to chain generator expressions:

data = [1, 2, 3, 4, 5, 6]

evens = (n for n in data if n % 2 == 0)
squares = (n * n for n in evens)

print(sum(squares))   # 56

A generator runs out

Like any iterator, a generator can only be traversed once. It is the most typical mistake:

gen = (x for x in range(3))

print(list(gen))   # [0, 1, 2]
print(list(gen))   # []  (it is already exhausted)

If you need to traverse it several times, store the values in a list or create the generator again.

What you cannot do with a generator

gen = (x for x in range(5))

# len(gen)      # TypeError: object of type 'generator' has no len()
# gen[0]        # TypeError: 'generator' object is not subscriptable

print(list(gen)[0])   # 0  (first you have to turn it into a list)

It has no length and cannot be indexed, because the values do not exist yet. You can only ask for the next one.

List or generator?

Use a list if…Use a generator if…
You need to traverse it several timesYou only traverse it once
You need len() or indexesThe data is very large or infinite
The data is smallYou want to start processing without waiting to have it all
You are going to sort or modify itYou chain several filtering or transforming stages