Advanced 12 min

Iterators and generators

An iterator hands you one value at a time, and a generator is a function that makes an iterator using yield.

How it works

Run the countdown in your head. The first request yields 3. When the next request arrives, the function resumes, reduces n, and yields 2. After it yields 1 and reduces n to zero, the loop finishes. One request at a time is useful when values come from a large file.

Walk through an example

Calling a generator creates an iterator. The first next() runs until yield, saves the function’s position, and gives you a value. The next call resumes from that position.

What to watch for

A generator is normally consumed only once. If a second pass is required, create a new generator or keep the values if they fit in memory.

Code example

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

print(list(countdown(3)))

Check your understanding

What does list(g) contain?

See the example and explanation
Worked example
Given g = iter([4, 9]); next(g); list(g)
Answer [9]

Calling next already consumed 4. The list loop collects only the remaining 9.

Open practice problem
Next lessonDecorators and function wrapping