← Python lessons

Python Generator close(): Stopping a Generator

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

A generator's close() method stops that generator when you no longer need more values.

You will close an infinite generator and understand why it cannot resume afterward. Prerequisites: basic functions, variables, loops, and Infinite Generators in Python: Running State. No imports are needed.

Close after taking the values you need

def counting():    number = 1    while True:        yield number        number += 1values = counting()for _ in range(3):    print(next(values))values.close()

This prints 1, 2, 3. values.close() stops this generator; it does not print anything or consume the remaining sequence. Unlike a pause at yield, closing is final. Merely stopping your printing loop leaves the generator paused and available for more requests.

A closed generator cannot resume

def counting():    number = 1    while True:        yield number        number += 1values = counting()print(next(values))values.close()print(next(values))  # this line raises StopIteration: values is closed

This prints 1, then raises StopIteration. Calling counting() again creates a separate generator starting at 1. Calling close() again on an already closed generator has no effect.

For a suspended generator, close() raises GeneratorExit at its paused yield. Normally this ends the function. If the function has an active try/finally, its finally block runs for cleanup. You do not need exception handling for these number generators. Use close() when you want to explicitly finish early, especially when a generator owns resources.

Remember two consecutive values

The Fibonacci sequence starts with 0 and 1; each later number is the sum of the previous two. This gives 0, 1, 1, 2, 3, 5, 8, 13.

When updating two related variables, save any calculation that needs their old values before changing them. This small example moves a pair forward once:

current = 4following = 7next_value = current + followingcurrent = followingfollowing = next_valueprint(current)print(following)

This prints 7, then 11. A generator can remember a pair between requests. The exercise combines that state update with an infinite loop and yield.

See also: Infinite Generators in Python: Running State. Reference: Python generator methods.

Your turn

Create fives(), an infinite generator producing multiples of five starting at 5. Print its first three values, then close it.

🎯 Goal — make it print exactly:
5
10
15
# Define fives(), print three requested values, then close the generator.

The output check verifies the printed values. Check that your final line closes the generator; closing itself produces no output.