Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Advanced Python & Software Engineering — Alpha School

Lesson 7: Generators and Lazy Evaluation

A list comprehension builds the whole list at once. For a million items, that means a million values sitting in memory before you use even one of them. A generator takes the opposite approach: it produces values one at a time, only when asked, and forgets each value as soon as you move on. That idea is called lazy evaluation, and it is what lets Python handle enormous — even infinite — sequences with almost no memory at all.

You write a generator function almost like a normal function, except that instead of return you use yield. Calling the function does not run any of its code; it returns a generator object. Each call to next() runs the function until the next yield, hands you that value, and freezes the function exactly where it stopped — local variables and all. When the function runs out of yields, the generator raises StopIteration, just like any other iterator. The countdown example from Lesson 5, which needed two whole classes, becomes a few lines:

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


gen = countdown(3)
print(next(gen))  # 3
print(next(gen))  # 2
print(list(gen))  # [1] — the rest is consumed by list()

# An infinite sequence costs almost no memory:
def squares():
    n = 1
    while True:
        yield n * n
        n += 1


s = squares()
print([next(s) for _ in range(4)])  # [1, 4, 9, 16]

Generator expressions

Just as list comprehensions have a lazy cousin, so does every comprehension you met in the last lesson. A generator expression looks identical except for the brackets: (x * x for x in range(10)) uses round brackets and builds nothing until you iterate. That makes it the right tool for pipelines — for example, summing the squares of a huge range without ever storing them: sum(x * x for x in range(10_000_000)) uses a tiny, fixed amount of memory, while the list version would build a ten-million-item list first. The underscore in 10_000_000 is just Python's way of letting you group digits for readability; it changes nothing about the number.

There is one catch to remember: a generator can only be consumed once. After you have pulled every value out of it, it is empty, and iterating again gives you nothing. If you need the values twice, either build a list or call the generator function again to get a fresh generator. That single-use nature is the price of laziness, and it is usually a good trade — but it is also the most common generator bug, so keep it in mind whenever a loop over a generator mysteriously produces nothing the second time.

Going further

Generators can delegate to other generators with yield from, which hands over control to a sub-generator until it is exhausted. A function that yields from two generators in sequence produces all the values of the first, then all the values of the second — a tidy way to chain sequences together without writing the loop yourself. It also works recursively: a function that walks a nested structure can yield from its own recursive calls, producing a flat stream of values from a tree. The syntax is small, but it removes a surprising amount of bookkeeping code.

It helps to have a feel for what laziness actually saves. A list of a million numbers holds a million objects in memory at once; a generator producing the same numbers holds only its current state — a handful of variables — no matter how many values it will eventually produce. That is why generators are the right tool for reading large files, processing streams of data, and searching through possibilities that might never end. The price, as the lesson says, is that a generator is single-use. When you need to revisit the data, build a list; when you only need to pass through it once, a generator is lighter in every way.

Try measuring the difference laziness makes. In the interactive prompt, build a list of the squares of the first million numbers with a list comprehension, and then build a generator expression for the same values, and compare them with sys.getsizeof — you will need to import the sys module first. The list reports a size in the tens of megabytes, while the generator reports a tiny fixed size, because it holds only its current state. The numbers will vary between machines, so do not quote them as facts; the point is the orders of magnitude. It is one thing to be told that generators save memory, and quite another to watch the difference appear on your own screen.

Key Terms

Generator
A function that uses yield to produce values one at a time, pausing between each one.
yield
The keyword that pauses a generator function, hands a value to the caller, and resumes later from the same point.
Lazy evaluation
Computing values only when they are asked for, instead of building everything up front.
Generator expression
A lazy comprehension in round brackets, such as (x * x for x in range(10)).
Generator object
The iterator returned by calling a generator function; its code has not run yet.
Infinite sequence
A sequence with no end, such as all square numbers; only possible with lazy evaluation.
Single-use
A generator can be consumed only once; after exhaustion it yields nothing more.

Discussion Questions

  1. Why does sum(x * x for x in range(10_000_000)) use almost no memory, while sum([x * x for x in range(10_000_000)]) needs a huge list?
  2. When would you still choose a list over a generator, even though the generator uses less memory?
  3. The infinite squares generator never ends. What would happen if you passed it to list()? How should you consume an infinite generator safely?

Practice Questions

  1. What does calling countdown(3) do immediately?
  2. What happens on the third next() after the generator is exhausted?
  3. Write a generator function that yields the even numbers from 0 up to (not including) n.
  4. Turn [x * 2 for x in range(5)] into a generator expression.
  5. You loop over a generator twice; the second loop prints nothing. Why?
Show answers
  1. Nothing except return a generator object. The function body does not run until the first next() call.
  2. It raises StopIteration. The function has run out of yields, so the iterator protocol signals the end.
  3. def evens(n): for i in range(0, n, 2): yield i Each yield pauses the loop; the caller pulls values one at a time.
  4. (x * 2 for x in range(5)) — just swap square brackets for round ones. The expression is lazy now: nothing is computed until you iterate.
  5. The generator was already exhausted by the first loop. Generators are single-use; call the generator function again for a fresh one.
Keep reading to complete this lesson