Python Generators

1. What is a Generator

A generator is a special type of function that returns an iterator and yields values one at a time using the yield keyword instead of return.

def simple_generator():
    yield 1
    yield 2
    yield 3

gen = simple_generator()
print(next(gen))  # 1
print(next(gen))  # 2

Generators produce values lazily, improving memory efficiency.


2. Generator vs Normal Function

def normal_function():
    return 10
    return 20

def generator_function():
    yield 10
    yield 20

print(normal_function())          # 10
print(list(generator_function())) # [10, 20]

A normal function returns once; a generator yields multiple times.


3. Iterating Over a Generator

Generators integrate seamlessly with loops.


4. Generator State Preservation

Execution pauses and resumes, preserving internal state automatically.


5. Memory Efficiency of Generators

Unlike lists, generators do not load all data into memory.


6. Generator Expression

Similar to list comprehensions but return a generator object.


7. Using Generators with next()

Direct control over iteration flow.


8. Infinite Generator

Produces an infinite sequence until manually stopped.


9. Generator with try...finally

Ensures cleanup logic is executed after generator completion.


10. Real-World Generator Example (Streaming Data)

Ideal for processing large files or streaming data efficiently.


Last updated