yieldAdvanced Examples

Pauses a generator function and produces a value to the caller

yield from: delegating to sub-generators

Composing generators with yield from.

python
def flatten(nested):
    for item in nested:
        if isinstance(item, (list, tuple)):
            yield from flatten(item)
        else:
            yield item

data = [1, [2, 3], [4, [5, 6]], 7]
print(list(flatten(data)))

# yield from for composed generators
def gen_a():
    yield 1
    yield 2

def gen_b():
    yield 3
    yield 4

def combined():
    yield from gen_a()
    yield from gen_b()
    yield 5

print(list(combined()))
Expected Output
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5]

'yield from' delegates iteration to another iterable/generator. It flattens one level of nesting and properly propagates send() and throw().

Want to try these examples interactively?

Open Advanced Playground