Home → Advanced → Generators
Reading
0%

1 · Generator Functions

When a generator function is called, it returns a generator object without even beginning execution of the function. When next() is called, the function resumes execution until a yield is reached.

📖
Textbook Definition

"A generator is a function that remembers its state between calls. Unlike regular functions that start from the top every time, generators 'resume' where they left off." — Fluent Python

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

counter = countdown(3)
print(next(counter))  # 3
print(next(counter))  # 2
🔁 Return Value

Calling a generator function returns a generator iterator object. It does not return the value yielded; you must iterate over the generator object to retrieve values.

📚 See Also