Delegate iteration to another iterable using yield from.
What You Will Learn
yield from iterable forwards yielded items from a subiterator to the outer generator. It can also propagate generator send(), throw(), and close() interactions according to the generator protocol, making it useful for composition.
A generator can capture the return value of another generator using result = yield from subgenerator().
Many iterator tools are lazy. Creating the iterator does not necessarily perform the work; advancing it can consume the original source.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
def grouped_numbers():
yield from range(1, 4)
yield from [10, 20]
print(list(grouped_numbers()))
How the Example Works
- The function grouped_numbers defines reusable behavior; its body executes when it is called, not when it is declared.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression list(grouped_numbers()) prints [1, 2, 3, 10, 20]. Compare that result with the rule above before you change the argument.
Expected output from the example:
[1, 2, 3, 10, 20]
When You Would Use This
This pattern is useful in readers for CSV files, event streams, or paginated API results, where collecting everything in memory is unnecessary. Because iterator state advances when values are consumed, decide whether you need a reusable collection or a one-time pass. Keep files and connections open until their lazy consumers finish.
Practice: Modify the Code
Combine three short iterables into one generator.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Confusing yield from with yielding the entire list as one single element.
- Assuming yield from materializes a complete copy of the delegated iterable.
Key Takeaways
- Delegate iteration to another iterable using yield from.
- yield from iterable forwards yielded items from a subiterator to the outer generator.
- A generator can capture the return value of another generator using result = yield from subgenerator().