SyntaxStudy
Sign Up
Python Intermediate 10 min read

Generators

Python Generators

Generators produce values lazily using yield, saving memory for large datasets.

Generator Function

def count_up(limit):
    n = 0
    while n < limit:
        yield n
        n += 1

for num in count_up(5):
    print(num)

Generator Expression

squares = (x**2 for x in range(1000000))
print(next(squares))  # 0
print(next(squares))  # 1

Infinite Generator

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()
for _ in range(10):
    print(next(fib))
Pro Tip

Generators use __iter__ and __next__ — any for loop works with them.