Course contentsShow
← Python
Lesson 633 of 1,06010. Advanced Language FeaturesFree lesson

Delegating Sub-generator Tasks with Yield From

You will simplify complex generator hierarchies by using the yield from syntax to delegate iteration to sub-generators or other iterables.

In this lesson, you will learn how to flatten complex generator hierarchies and simplify your code by delegating iteration to sub-generators using the yield from syntax.

The Problem of Nested Loops

When you have a generator that needs to produce values from another generator (or any iterable), you typically use a nested loop. For example, if you want to flatten a list of lists, you might write this:

def flatten(list_of_lists):
    for sublist in list_of_lists:
        for item in sublist:
            yield item

While this works, it becomes cumbersome when you have multiple levels of delegation or need to handle complex generator communication.

The yield from Solution

Python’s yield from syntax allows a generator to delegate part of its operations to a sub-generator. It essentially acts as a transparent conduit, passing values directly from the sub-generator to the caller without requiring you to manually loop through them.

Refactoring the previous example is simple:

def flatten(list_of_lists):
    for sublist in list_of_lists:
        yield from sublist

# Usage
data = [[1, 2], [3, 4]]
for val in flatten(data):
    print(val)  # Outputs: 1, 2, 3, 4

Why Use yield from?

Beyond just making your code cleaner and more readable, yield from performs a crucial role in advanced generator communication. It establishes a direct "pipe" between the caller and the sub-generator. This means that if the caller sends data into the generator using .send() or closes it with .throw(), those actions are automatically passed down to the sub-generator.

If you were to use a standard for loop, you would have to manually implement that logic to forward those signals, which is error-prone and complex. By using yield from, you delegate the entire iterator protocol to the sub-generator, allowing you to focus on the high-level logic of your data pipeline rather than the plumbing of iteration.

Key Takeaway: The yield from syntax simplifies your code by automatically delegating iteration and communication from a delegator generator to a sub-generator.