Iterators and generators

yield, lazy evaluation and one-time streams.

for can go through more than lists. Any iterable object will do, one that hands out its elements one at a time on request. A list keeps all its elements in memory. A generator computes them on the fly and can produce endlessly many values without taking up memory.

A function with yield instead of return becomes a generator:

def countdown(n):
    while n > 0:
        yield n
        n -= 1

print(list(countdown(3)))   # [3, 2, 1]

When called, such a function runs nothing; it returns a generator object. Each next request (next or a step of a for loop) runs the code up to the nearest yield. There the function hands out a value and pauses until the next request. When the function ends, the iteration stops.

A generator expression is written like a list comprehension, but in round brackets: (x * x for x in range(10)). It is convenient to pass straight into functions: sum(x * x for x in range(10)) builds no intermediate list.

A generator can be used only once: after a full pass it is empty. This is a common source of silent bugs:

squares = (x * x for x in range(3))
print(sum(squares))   # 5
print(sum(squares))   # 0

If you need the data several times, keep it in a list: list(...). Generators are good for long streams, such as the lines of a big file or numbers that have to be checked one by one until a suitable one is found.

Practice

  1. The second pass

    What does the program print?

    g = (x for x in range(3))
    print(sum(g), sum(g))
    
  2. What yield does

    What does yield do inside a function?

    • Hands out a value and pauses the function until the next request
    • Ends the function, like return
    • Prints the value on the screen
    • Creates a list of all the values at once
  3. Squares up to a limit

    Write a generator squares_up_to(limit) that yields the squares of the numbers 1, 2, 3 and so on — 1, 4, 9, … — as long as the square is not greater than limit.