⚡

How to Use Generators in Python

PythonAdvanced

Create memory-efficient iterators with generators.

Code Example

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

print("Countdown:")
for num in countdown(5):
    print(num, end=" ")

# Generator expression
squares = (x**2 for x in range(10))
print(f"\n\nSquares: {list(squares)}")

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

fib = fibonacci()
print("\nFirst 10 Fibonacci:")
for _ in range(10):
    print(next(fib), end=" ")

# Generator with send
def accumulator():
    total = 0
    while True:
        value = yield total
        if value is None:
            break
        total += value

acc = accumulator()
next(acc)  # Start generator
print(f"\n\nAccumulator: {acc.send(10)}")
print(f"Accumulator: {acc.send(20)}")
print(f"Accumulator: {acc.send(30)}")

# Generator pipeline
def read_data():
    for i in range(5):
        yield i

def process_data(data):
    for item in data:
        yield item * 2

pipeline = process_data(read_data())
print(f"\nPipeline: {list(pipeline)}")

Explanation

Generators use yield to produce values lazily. Memory efficient for large sequences. Generator expressions use () instead of []. Can send values with send().

Related Tutorials