SyntaxStudy
Sign Up
Python Intermediate 4 min read

Generator Functions

Generator Functions

A function with a yield statement becomes a generator function. Calling it returns a generator iterator that produces values lazily.

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

for val in countdown(5):
    print(val)  # 5 4 3 2 1
Pro Tip

Generators maintain their state between yields — no manual tracking needed.