Iteration

Yield From

yield from delegates part of a generator to another iterable.

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']
OUTERyield from innerINNER
`yield from inner` delegates iteration to an inner generator; its yields surface here unchanged.

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

See also

Run the complete example

Example code

Expected output

['header', 'intro', 'body', 'footer']
[1, 2, 3]

Execution time appears here after you run the example.