Iteration
Yield From
yield from delegates to another iterable. The caller receives one stream even though part of it came from a list.
Source
def page():
yield "header"
yield from ["intro", "body"]
yield "footer"
print(list(page()))Output
['header', 'intro', 'body', 'footer']Delegation is useful when flattening nested iterables. yield from row replaces an inner loop that would yield each item by hand.
Source
def flatten(rows):
for row in rows:
yield from row
print(list(flatten([[1, 2], [3]])))Output
[1, 2, 3]Notes
yield from iterableyields each value from that iterable.- It keeps generator pipelines compact.
- Use a plain
yieldwhen producing one value directly.
See also
- prerequisite: Generators
- related: Generator Expressions
- related: Itertools
Run the complete example
Expected output
['header', 'intro', 'body', 'footer']
[1, 2, 3]
Execution time appears here after you run the example.