Browse Python Topics ▼
Pick a Web Framework

Generators and Lazy Evaluation with Yield

📂 Advanced Python 📘 Lesson 42 of 57

Stream data with zero memory bloat using Python generators. Master the yield keyword, generator expressions, state preservation, and infinite streams.

Imagine you want a glass of fresh water.

  • The Traditional List Approach: Someone delivers a 10,000-gallon tanker truck of water and dumps it entirely into your living room before letting you drink a single sip.
  • The Generator Approach: You walk over to your kitchen faucet, turn the handle, and water pours out one cup at a time as you need it.

In computer programming, if you generate a list of 10,000,000 numbers, your computer has to allocate hundreds of megabytes of RAM upfront to store all 10 million integers simultaneously before your loop can even begin.

If your computer runs out of RAM, your application crashes with a fatal MemoryError.

To solve this, Python gives you Generators: special functions that produce values lazily—one at a time on demand—with virtually zero memory overhead.


1. The yield Keyword (The Pause Button)

In a regular function, return hands back a final result and permanently destroys the function’s local execution state.

When Python sees the yield keyword inside a function, something magical happens:

  1. Python converts the function into a Generator.
  2. Calling the function does not run the code; it returns a generator iterator.
  3. When next() is called, the function executes until it reaches yield.
  4. It yields the value and freezes in place! All local variables and loop positions are preserved in memory.
  5. The next time next() is called, the function resumes immediately from where it paused!
def simple_counter():
    print("--> Starting counter")
    yield 1
    print("--> Resumed after 1")
    yield 2
    print("--> Resumed after 2")
    yield 3
    print("--> Counter finished!")

# Calling the function returns a generator object:
gen = simple_counter()

print("Step 1:", next(gen))
print("Step 2:", next(gen))
print("Step 3:", next(gen))

# Next call raises StopIteration:
# next(gen)

Output:

--> Starting counter
Step 1: 1
--> Resumed after 1
Step 2: 2
--> Resumed after 2
Step 3: 3

2. Real-World Memory Benchmark

Let’s test the memory difference between a traditional list and a lazy generator using Python’s sys.getsizeof():

import sys

# 1. A List holding 1,000,000 numbers in RAM:
huge_list = [x for x in range(1_000_000)]

# 2. A Generator capable of producing 1,000,000 numbers lazily:
huge_gen = (x for x in range(1_000_000))

print(f"List memory size:      {sys.getsizeof(huge_list):,} bytes")
print(f"Generator memory size: {sys.getsizeof(huge_gen):,} bytes")

Output:

List memory size:      8,448,728 bytes (~8.5 Megabytes)
Generator memory size:       112 bytes

The generator is 75,000 times lighter on RAM! Whether you generate 10 numbers, 10 million numbers, or 10 billion numbers, the generator always uses roughly 112 bytes.


3. Generator Expressions (Comprehensions with ())

Just as square brackets [...] create a list comprehension in comprehensions, replacing the brackets with parentheses (...) creates a Generator Expression:

# List comprehension: Evaluated immediately (eager)
squares_list = [x ** 2 for x in range(5)]
print("List:", squares_list)  # [0, 1, 4, 9, 16]

# Generator expression: Evaluated lazily on demand
squares_gen = (x ** 2 for x in range(5))
print("Gen:", squares_gen)    # <generator object <genexpr> at 0x7f...>

# Loop through generator lazily:
for sq in squares_gen:
    print(sq, end=" ")
print()

4. Modeling Infinite Streams

Because generators only compute values when asked, you can safely write infinite loops without hanging your computer:

def transaction_id_generator():
    """Generates continuous unique tracking IDs forever."""
    current_id = 1001
    while True:
        yield f"TXN-{current_id}"
        current_id += 1

id_stream = transaction_id_generator()

print(next(id_stream))  # TXN-1001
print(next(id_stream))  # TXN-1002
print(next(id_stream))  # TXN-1003

5. Streaming Data Pipelines

Generators can be chained together into elegant, memory-efficient data processing pipelines:

# Simulated raw server log lines
log_lines = [
    "2026-10-13 10:00:01 INFO User logged in",
    "2026-10-13 10:00:05 ERROR Database timeout",
    "2026-10-13 10:00:12 INFO Cache refreshed",
    "2026-10-13 10:00:19 ERROR Connection refused"
]

# Pipeline Stage 1: Filter error lines only
error_stream = (line for line in log_lines if "ERROR" in line)

# Pipeline Stage 2: Extract error message payload
message_stream = (line.split("ERROR")[1].strip() for line in error_stream)

# Consume pipeline:
print("Detected errors:")
for msg in message_stream:
    print(f"  Alert: {msg}")

Output:

Detected errors:
  Alert: Database timeout
  Alert: Connection refused

Each log line flows through Stage 1 and Stage 2 one by one without ever buffering all intermediate results into lists!


Summary & What’s Next

  • Generators evaluate data lazily on demand using the yield keyword.
  • When yield is reached, execution pauses and saves local state until next() is called.
  • Use generator expressions (...) instead of list comprehensions when processing large datasets.
  • Generators enable infinite data streams and memory-efficient data processing pipelines.

Now that you know how to pause and resume function execution, how do you modify or wrap function behavior dynamically without altering its source code? Learn about decorators.

Test your understanding of Generators and Lazy Evaluation with Yield

Quick interactive practice questions with instant feedback.

Take Quiz →