Back to series
· 15 min read

Python Generators and Lazy Evaluation


I. What Is a Generator

A generator is a special kind of iterator in Python that can pause during execution and resume from the paused position the next time data is requested.

Ordinary functions usually return results via return, and once the function finishes executing it does not continue; generator functions, by contrast, produce results one at a time via yield, pause when execution reaches yield, and preserve the current execution state.

1. Ordinary Functions vs. Generator Functions

Ordinary function:

def get_numbers():
    return [1, 2, 3]


result = get_numbers()

print(result)
# [1, 2, 3]

This function creates the list all at once and returns all its results.

Generator function:

def get_numbers():
    yield 1
    yield 2
    yield 3


result = get_numbers()

print(result)
# <generator object get_numbers at ...>

When a generator function is called, the function body is not executed immediately; instead, a generator object is returned.

The generator begins executing only when the next element is requested.

generator = get_numbers()

print(next(generator))  # 1
print(next(generator))  # 2
print(next(generator))  # 3

If data continues to be requested after the generator has no more elements, it raises StopIteration.

2. Core Characteristics of Generators

Feature Description
Produce data on demand Execute the corresponding logic only when an element is needed
Pause and resume Pause at yield and continue on the next request
Preserve execution state Retain local variables and execution position
Lazy evaluation No need to compute all results in advance
Iterator protocol Supports iter(), next(), and for
One-time consumption Does not automatically restart after normal exhaustion
Composition Can be combined with other iterators to form a data processing pipeline

3. Relationship Between Generators and Iterators

A generator is a special implementation of an iterator.

A generator object has all of the following:

  • __iter__(): returns itself.
  • __next__(): executes the generator and obtains the next result.
  • send(): sends a value into the generator.
  • throw(): injects an exception into the generator.
  • close(): requests that the generator be closed.

This can be understood through the following abstract relationship:

flowchart TD
    A["Iterable Object"] --> B["iter()"]
    B --> C["Iterator"]
    C --> D["Generator"]
    D --> E["yield Pause and Resume"]
    E --> F["Produce Data on Demand"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155

II. yield: The Core Syntax of Generators

yield is the core keyword of generators.

Both it and return can provide results to the caller, but their execution semantics differ.

1. Differences Between yield and return

Comparison Dimension return yield
Result returned Returns the function result Produces an iteration value
Execution state Ends the current function call Pauses generator execution
Local variables The function call ends Retained while paused
Subsequent execution Does not continue the original function call Resumes on the next request
Use case Ordinary functions Generator functions

Example:

def normal_function():
    print("开始执行")
    return 100
    print("不会执行")


def generator_function():
    print("开始执行")
    yield 100
    print("继续执行")
    yield 200
    print("执行结束")


print(normal_function())

generator = generator_function()

print(next(generator))
print(next(generator))

Output:

Start execution
100
Start execution
100
Continue execution
200

On the second call to next(), the generator continues executing after the previous yield.

2. Execution Order of yield

Calling a generator function differs from calling a normal function.

def generate():
    print("步骤一")
    yield 1

    print("步骤二")
    yield 2

    print("步骤三")
    yield 3


generator = generate()

print("生成器创建完成")

print(next(generator))
print(next(generator))
print(next(generator))

Execution process:

  1. Call generate() to create a generator object.
  2. The function body is not executed.
  3. The first call to next() runs up to the first yield.
  4. The second call to next() resumes from the paused position.
  5. The third call to next() continues execution up to the third yield.

The flow is as follows:

flowchart TD
    A["Call generator function"] --> B["Create generator object"]
    B --> C["Call next()"]
    C --> D["Execute generator function"]
    D --> E{"Encounter yield?"}
    E -->|Yes| F["Return current value and pause"]
    F --> G["Save execution state"]
    G --> H["Call next() again"]
    H --> D
    E -->|No| I["Function execution ends"]
    I --> J["Raise StopIteration"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style J fill:#FBE9E9,stroke:#D9AAAA,color:#334155

3. yield Can Produce Multiple Results

A generator function can contain multiple yield expressions.

def generate_colors():
    yield "red"
    yield "green"
    yield "blue"


for color in generate_colors():
    print(color)

It can also generate data dynamically in a loop:

def generate_numbers(count):
    for number in range(count):
        yield number


for number in generate_numbers(5):
    print(number)

This approach does not require creating the full list in advance.

4. yield Can Be Followed by an Expression

yield can produce variables, calculation results, objects, or function return values.

def calculate():
    a = 10
    b = 20

    yield a + b
    yield a * b
    yield a ** 2


for result in calculate():
    print(result)

Output:

30
200
100

5. yield and return can be used together

A generator function can contain return.

Here:

  • yield is responsible for producing an iteration value.
  • return ends the generator.
  • return value places the return value into StopIteration.value.
def generate():
    yield 1
    yield 2
    return "生成结束"


generator = generate()

print(next(generator))
print(next(generator))

try:
    next(generator)
except StopIteration as exc:
    print(exc.value)

Output:

1
2
生成结束

Note that an ordinary for loop automatically handles StopIteration and will not output its value as a normal iteration element.


III. Generator Functions and Generator Objects

To understand generators, you need to distinguish between two concepts:

  • Generator function: a function definition that contains yield.
  • Generator object: the object obtained after calling a generator function.

1. Generator Function

def count():
    yield 1
    yield 2
    yield 3

This defines a generator function.

You can check it using the inspect module:

import inspect

print(inspect.isgeneratorfunction(count))
# True

2. Generator Object

Call the generator function:

generator = count()

This returns a generator object.

import inspect

print(inspect.isgenerator(generator))
# True

3. Calling a Generator Function Multiple Times Creates Different Objects

def generate():
    yield 1
    yield 2


generator1 = generate()
generator2 = generate()

print(generator1 is generator2)
# False

The two generator objects have independent execution states.

generator1 = generate()
generator2 = generate()

print(next(generator1))  # 1
print(next(generator1))  # 2

print(next(generator2))  # 1

Consuming one generator object does not automatically advance the other generator object.

4. Basic Properties of Generator Objects

You can use inspect to view the generator's state.

import inspect


def generate():
    yield 1
    yield 2


generator = generate()

print(inspect.getgeneratorstate(generator))
# GEN_CREATED

next(generator)

print(inspect.getgeneratorstate(generator))
# GEN_SUSPENDED

next(generator)

try:
    next(generator)
except StopIteration:
    pass

print(inspect.getgeneratorstate(generator))
# GEN_CLOSED

Common states:

State Meaning
GEN_CREATED Created but not yet started execution
GEN_RUNNING Executing
GEN_SUSPENDED Suspended at a yield position
GEN_CLOSED Finished execution or closed

These states help when debugging complex generators.


IV. Generator Expressions

In addition to generator functions, Python also provides generator expressions (Generator Expression).

Generator expressions are created using parentheses and provide a concise way to express lazy data computation.

1. Basic Syntax

(expression for item in iterable)

For example:

numbers = (x * 2 for x in range(5))

print(numbers)
# <generator object ...>

When you need to consume it:

for number in numbers:
    print(number)

2. Differences from List Comprehensions

List comprehension:

numbers = [x * 2 for x in range(5)]

print(numbers)
# [0, 2, 4, 6, 8]

Generator expression:

numbers = (x * 2 for x in range(5))

print(numbers)
# <generator object ...>

Differences between the two:

Aspect List comprehension Generator expression
Syntax [] ()
Return type list generator
Evaluation timing Computes all elements immediately Computes elements on demand
Memory usage Stores all results Usually stores only the state currently needed
Supports indexing? Yes No
Can be iterated multiple times? Yes The same generator can usually be consumed only once
Use cases When a complete result set is needed When the data volume is large or elements only need to be processed one by one

3. Conditional Filtering in Generator Expressions

numbers = (x for x in range(20) if x % 2 == 0)

for number in numbers:
    print(number)

The generator only produces elements that meet the condition.

4. Generator Expressions with Multiple Loops

pairs = (
    (x, y)
    for x in range(3)
    for y in range(3)
    if x != y
)

for pair in pairs:
    print(pair)

Its loop order is the same as nested for loops.

5. Conditional Expressions and Generator Expressions

numbers = (
    x * 2 if x % 2 == 0 else x
    for x in range(10)
)

for number in numbers:
    print(number)

Here, the conditional expression is responsible for computing the result, while the generator expression produces results on demand.

6. Generator Expressions as Function Arguments

When a generator expression is the only positional argument to a function, the outer parentheses can usually be omitted.

numbers = [1, 2, 3, 4, 5]

result = sum(x * 2 for x in numbers)

print(result)
# 30

This saves memory for intermediate results compared with creating a list first and then summing it.

7. Evaluation Timing of Generator Expressions

Generator expressions are lazy, but not every part is deferred until the first iteration.

When a generator expression is created, the iterable expression in the outermost for clause is evaluated immediately; the element expression, filter conditions, and subsequent iteration steps are executed on demand during consumption.

For example:

def get_data():
    print("获取数据源")
    return [1, 2, 3]


generator = (x * 2 for x in get_data())

print("生成器已创建")

print(next(generator))

Output:

获取数据源
生成器已创建
2

get_data() is executed when the generator expression is created, while x * 2 is computed when an element is requested.


V. Lazy Evaluation

Lazy evaluation is one of the most important benefits of generators.

It means that a computation does not do all its work immediately; instead, it executes only when the result is actually needed.

1. What Is Lazy Evaluation?

Suppose you need to process one million pieces of data.

With immediate evaluation:

numbers = [x * 2 for x in range(1000000)]

The program creates a list containing one million computed results.

With lazy evaluation:

numbers = (x * 2 for x in range(1000000))

The program creates a generator object but does not compute all the results immediately.

It computes them step by step only when next() is called or the data is consumed with a for loop.

2. Lazy Evaluation vs. Immediate Evaluation

Dimension Eager Evaluation Lazy Evaluation
Execution timing When the result is created When data is requested
Calculation scope Usually computes all results Computes only the part actually consumed
Memory overhead May be larger Usually smaller
Repeated access Can directly access stored results Usually requires recomputation or caching
Debugging approach Results are already built and easy to inspect Execution timing may be scattered
Typical tools List comprehensions Generator expressions, generator functions

3. Example of On-Demand Computation

def generate_numbers():
    for number in range(5):
        print(f"正在计算:{number}")
        yield number * 10


generator = generate_numbers()

print("生成器创建完成")

print(next(generator))
print(next(generator))

Output:

生成器创建完成
正在计算:0
0
正在计算:1
10

Consuming only two elements executes only the first two computation steps.

4. Core Flow of Lazy Evaluation

flowchart TD
    A["Create generator"] --> B["Wait for consumption request"]
    B --> C["Call next()"]
    C --> D["Execute current computation"]
    D --> E{"Produce a result?"}
    E -->|Yes| F["Return current element"]
    F --> G["Pause and preserve state"]
    G --> B
    E -->|No| H["End generator"]
    H --> I["Raise StopIteration"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style I fill:#FBE9E9,stroke:#D9AAAA,color:#334155

5. Lazy Evaluation Does Not Mean Never Computing

A generator performs the corresponding computation only when it is consumed.

If it is eventually executed:

result = list(generator)

then all remaining elements in the generator will be consumed, and a list will still ultimately be constructed.

Therefore, the value of lazy evaluation lies in deferring and controlling the computation process, not in guaranteeing that no computation will ever happen.

6. Lazy Evaluation and Short-Circuit Evaluation

Lazy evaluation is also often combined with short-circuit evaluation.

For example:

numbers = (x for x in range(1000000))

result = any(x > 100 for x in numbers)

print(result)
# True

After any() finds the first truthy value that satisfies the condition, it stops consuming the generator.

Therefore, there is no need to traverse all the remaining data.

Similarly:

numbers = (x for x in range(1000000))

result = all(x >= 0 for x in numbers)

print(result)
# True

Only if all elements are true will all() consume the entire iterator.

If a false value appears along the way, it stops early.


VI. Execution State and Lifecycle of Generators

A generator is not a simple data container, but an execution object that can be paused and resumed.

1. How Generators Preserve State

def counter():
    number = 1

    while number <= 3:
        print("准备产生数据")
        yield number

        number += 1


generator = counter()

print(next(generator))
print(next(generator))

The first call to next():

  1. When created, the function body has not yet been executed.
  2. The function starts executing.
  3. Initialize number.
  4. Execution reaches yield number.
  5. Return 1 and pause.

Second call to next():

  1. Resume from the previous suspension point.
  2. Execute number += 1.
  3. Evaluate the loop condition.
  4. Execute yield again.
  5. Return 2 and pause.

2. Generator State Transitions

flowchart TD
    A["GEN_CREATED"] --> B["First call to next()"]
    B --> C["GEN_RUNNING"]
    C --> D["Reaches yield"]
    D --> E["GEN_SUSPENDED"]
    E --> F["Call next() again"]
    F --> C
    C --> G["Execution ends or is closed"]
    G --> H["GEN_CLOSED"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style H fill:#FBE9E9,stroke:#D9AAAA,color:#334155

3. Checking Generator State

import inspect


def generate():
    yield 1
    yield 2


generator = generate()

print(inspect.getgeneratorstate(generator))
# GEN_CREATED

next(generator)

print(inspect.getgeneratorstate(generator))
# GEN_SUSPENDED

After the generator finishes execution:

try:
    while True:
        next(generator)
except StopIteration:
    pass

print(inspect.getgeneratorstate(generator))
# GEN_CLOSED

4. A Generator Cannot Be Restarted After Being Closed

def generate():
    yield 1
    yield 2


generator = generate()

print(next(generator))

generator.close()

print(next(generator))

Requesting data again after it is closed raises StopIteration.

If you need to start over, call the generator function again to create a new generator object.

5. A Generator's Execution State Is Not a Data Cache

A generator stores the state needed to continue execution, rather than caching all already-produced results by default.

For example:

def generate():
    for number in range(1000000):
        yield number

This generator does not automatically store one million results just because it has produced the preceding elements.

If you need to repeatedly read past results, you need to use a list, cache, or another storage structure separately.


VII. Advanced Generator Interfaces

In addition to next(), generators also provide methods such as send(), throw(), and close().

These interfaces allow a generator not only to provide data outward but also to receive external input, handle exceptions, and control the execution process.

1. send(): Sending Data to a Generator

send() can send a value to a generator.

This value becomes the result of the yield expression at the current suspension point.

def calculator():
    while True:
        number = yield
        print("收到数据:", number)


generator = calculator()

next(generator)

generator.send(10)
generator.send(20)
generator.send(30)

Output:

Received data: 10
Received data: 20
Received data: 30

Here, the first call to next() starts the generator, causing it to run to the first yield and pause.

You can also use:

generator.send(None)

Perform the same startup operation.

Note: a newly created generator has not yet paused at the yield expression, so you cannot directly send it a non-None value; otherwise, a TypeError will be raised.

2. The yield expression receives the value from send()

def calculator():
    result = 0

    while True:
        number = yield result
        result += number


generator = calculator()

print(next(generator))
# 0

print(generator.send(10))
# 10

print(generator.send(20))
# 30

print(generator.send(5))
# 35

Execution logic:

  1. On the first startup, the initial result 0 is produced.
  2. Send 10; it is assigned to number, and the accumulated result is updated.
  3. Execution reaches yield again, producing 10.
  4. Send 20, and the accumulated result becomes 30.
  5. As more data is sent, the generator continues to update its state.

3. The execution process of send()

flowchart TD
    A["Create generator"] --> B["next() starts"]
    B --> C["Execution reaches yield"]
    C --> D["Wait for external input"]
    D --> E["send(value)"]
    E --> F["yield expression receives value"]
    F --> G["Execute internal logic"]
    G --> C

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155

4. throw(): Injecting exceptions into a generator

throw() can inject an exception into a generator while it is paused.

If the exception is caught inside the generator, the corresponding handling logic can be executed.

def generate():
    try:
        yield 1
        yield 2
    except ValueError:
        print("捕获到 ValueError")
        yield 100

    yield 3


generator = generate()

print(next(generator))
print(generator.throw(ValueError))
print(next(generator))

Output:

1
捕获到 ValueError
100
3

Here, the ValueError is injected into the generator and caught by try...except.

If the exception is not handled inside the generator, it propagates to the caller.

5. close(): Closing a generator

close() is used to request that the generator be closed.

It injects a GeneratorExit exception into the generator.

def generate():
    try:
        yield 1
        yield 2
    finally:
        print("执行清理操作")


generator = generate()

print(next(generator))

generator.close()

Output:

1
执行清理操作

When a generator is closed, it is a good time to perform resource cleanup, such as closing files, releasing connections, or clearing temporary state.

Keep in mind:

  • GeneratorExit is the exception used when closing a generator.
  • Cleanup logic in finally will execute normally.
  • A generator should not continue producing normal data after receiving the close signal.
  • If a generator ignores the close signal and continues to yield, close() will raise a RuntimeError.

6. yield from: Delegating to a subgenerator

yield from can delegate the iteration process to another iterable or generator.

def generate_numbers():
    yield 1
    yield 2
    yield 3


def generate_all():
    yield from generate_numbers()
    yield 4
    yield 5


for number in generate_all():
    print(number)

Output:

1
2
3
4
5

Equivalent to:

def generate_all():
    for number in generate_numbers():
        yield number

    yield 4
    yield 5

But yield from is more than just a syntax simplification.

It can also delegate generator protocol operations such as send(), throw(), and close() to the sub-generator, and obtain its return value when the sub-generator finishes.

7. Using yield from to get the sub-generator's return value

def sub_generator():
    yield 1
    yield 2
    return "子生成器结束"


def main_generator():
    result = yield from sub_generator()
    yield result


for item in main_generator():
    print(item)

Output:

1
2
子生成器结束

The sub-generator's return value does not automatically become a regular iteration element; instead, it becomes the result of the yield from expression.

This allows generators to be composed in more complex layers.


8. Generators and Coroutines

Generators and coroutines have historical and mechanical connections, but the two cannot simply be regarded as the same concept.

1. Generators can implement cooperative control

Through yield and send(), a generator can alternate between multiple execution stages.

def task(name):
    while True:
        message = yield
        print(f"{name} 收到:{message}")


task_a = task("任务 A")
task_b = task("任务 B")

next(task_a)
next(task_b)

task_a.send("处理订单")
task_b.send("发送通知")
task_a.send("更新状态")

Here the generators can suspend execution and resume when driven from the outside.

This capability was an important foundation for early Python cooperative concurrency and coroutine implementations.

2. Generator coroutines and native coroutines

Modern Python provides async def and await for defining native coroutines.

Aspect Generator Native coroutine
How it is defined def + yield async def
Getting results next(), send() await
Returned object Generator object Coroutine object
Main use Lazy iteration, data generation Asynchronous control flow
Typical driving method for, next() asyncio event loop

Native coroutine example:

import asyncio


async def fetch_data():
    print("开始请求")
    await asyncio.sleep(1)
    return {"status": "success"}


async def main():
    result = await fetch_data()
    print(result)


asyncio.run(main())

Here await is used to wait for another awaitable to complete.

3. The relationship between generators and native coroutines

Early Python once used generators to implement coroutines, for example cooperative scheduling based on yield and yield from.

Modern Python uses the native coroutine protocol, which provides clearer asynchronous semantics.

Therefore:

  • Generators primarily address lazy iteration and producing data on demand.
  • Native coroutines primarily address suspending and resuming asynchronous tasks.
  • Both have the characteristics of suspension and resumption.
  • The two have different protocols and ways of being used.

Do not use an ordinary generator directly as an async def coroutine.


9. Generators and Memory Optimization

Generators are often used to process large datasets because they can avoid creating a large number of intermediate results all at once.

But it is important to understand: generators reduce unnecessary data storage; this does not mean they are always faster or use less memory in every scenario.

1. A list stores all data at once

numbers = [x * 2 for x in range(1000000)]

This creates a list containing one million results.

The list needs to store references to all elements as well as the container structure.

2. A generator produces data on demand

numbers = (x * 2 for x in range(1000000))

Here, only the generator object is created.

When the following is called:

print(next(numbers))

only then is the first result calculated and produced.

3. Memory usage comparison

import sys

numbers_list = [x for x in range(10000)]
numbers_generator = (x for x in range(10000))

print(sys.getsizeof(numbers_list))
print(sys.getsizeof(numbers_generator))

Usually, the size of the generator object itself is much smaller than that of a complete list.

But note that sys.getsizeof() only reports the shallow size of the object itself; it does not recursively calculate all the objects it references, nor can it represent the actual peak memory of the entire program.

4. Using tracemalloc to analyze memory

import tracemalloc


def build_list():
    return [x for x in range(100000)]


def build_generator():
    return (x for x in range(100000))


tracemalloc.start()

data = build_generator()

current, peak = tracemalloc.get_traced_memory()

print("当前内存:", current)
print("峰值内存:", peak)

tracemalloc.stop()

If you want to observe the memory changes after fully consuming the generator, you can measure further:

import tracemalloc


def generate_numbers():
    for number in range(100000):
        yield number


tracemalloc.start()

numbers = list(generate_numbers())

current, peak = tracemalloc.get_traced_memory()

print("当前内存:", current)
print("峰值内存:", peak)

tracemalloc.stop()

The second approach collects all results into a list, so the memory advantage of the generator is offset by the final list.

5. Generators are not necessarily faster than lists

Generators have some iteration and function-resumption overhead.

If the amount of data is small, or if frequent random access is needed, a list may be more appropriate.

Selection criteria:

Scenario More suitable approach
Small-scale data that needs repeated access List
Need indexing and slicing List
Line-by-line processing of large files Generator
Large data streams Generator
Only need to calculate summary values Generator expression
Need to cache all results List
Multi-stage data processing Generator pipeline
Need random access to historical elements List or other storage structure

10. Generator Pipelines and Data Stream Processing

Generators can not only save memory but can also be combined into data-processing pipelines.

Each generator is responsible for an independent processing step, and the data produced by the previous stage is passed directly to the next stage.

1. What Is a Generator Pipeline

A generator pipeline (Generator Pipeline) is a design approach that connects multiple iterative processing steps.

For example:

  1. Read raw data.
  2. Filter invalid data.
  3. Convert data format.
  4. Perform business calculations.
  5. Output processing results.

Each stage can produce results on demand.

2. Step 1: Generate raw data

def read_data():
    for number in range(1, 11):
        yield number

3. Step 2: Filter data

def filter_even(numbers):
    for number in numbers:
        if number % 2 == 0:
            yield number

4. Step 3: Transform data

def transform(numbers):
    for number in numbers:
        yield number * 10

5. Step 4: Combine processing

result = transform(
    filter_even(
        read_data()
    )
)

for number in result:
    print(number)

Output:

20
40
60
80
100

6. Generator pipeline flow

flowchart LR
    A["Raw data source"] --> B["read_data()"]
    B --> C["filter_even()"]
    C --> D["transform()"]
    D --> E["Output result"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

7. Building a pipeline with map and filter

numbers = range(1, 11)

result = map(
    lambda x: x * 10,
    filter(
        lambda x: x % 2 == 0,
        numbers
    )
)

for number in result:
    print(number)

Both map() and filter() can return lazy iteration results.

8. Combining data streams with itertools

itertools can further simplify complex iteration pipelines.

from itertools import islice, chain


def generate_numbers():
    yield from range(1, 100)


numbers = chain(
    generate_numbers(),
    [100, 101, 102]
)

result = islice(numbers, 10)

print(list(result))