← Python lessons

Python yield: Write a Generator Function

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A generator function uses yield to supply a value and pause until the next request.

You will write a generator function and read it with a for loop and next(). Prerequisites: functions, for loops, lists, and Python Generators: Your First Generator and next(). No imports are needed.

Build a list or yield each value

Both functions make the squares of 0, 1 and 2. The print("making", i) lines are only there to show when each value is made.

def squares_list(n):    result = []    for i in range(n):        print("making", i)        result.append(i * i)    return resultdef squares_yield(n):    for i in range(n):        print("making", i)        yield i * ifor sq in squares_list(3):    print("got", sq)print()for sq in squares_yield(3):    print("got", sq)

squares_list() makes all three values before the loop gets any. squares_yield() makes one value, pauses at yield, and continues when the loop asks for the next.

Use a list when you need to index the values or read them again. Use yield when the values are read once, in order.

Calling the function runs nothing yet

Using yield inside a function makes it a generator function. Calling it creates a generator without running the body. Each next() runs the body up to the next yield.

def squares_yield(n):    for i in range(n):        print("making", i)        yield i * ivalues = squares_yield(3)print("created")print(next(values))print(next(values))

created prints before making 0. The second next(values) continues after the pause, so it prints making 1 and 1.

A for loop makes these next() requests for you. Calling squares_yield(3) again creates a new generator that starts from the beginning.

yield pauses; return ends

return gives back a result and finishes the function. yield gives back a value and pauses. When the function body ends, the generator is finished and another next() raises StopIteration.

def one_value():    yield 7value = one_value()print(next(value))  # 7print(next(value))  # this line raises StopIteration: the function has ended

This prints 7, then raises StopIteration. A for loop stops quietly at this point instead.

See also: Python Generators: Your First Generator and next().

Your turn

Write a generator function called countdown() that uses a loop over [3, 2, 1] and yields each number. Store its generator and print its three values with next().

🎯 Goal — make it print exactly:
3
2
1
# Define countdown(), create its generator, then print its three values.