Skip to content

yield from

In one line

'yield from sub_gen' yields every value from sub_gen, enabling clean generator delegation and composition.

In simple words

The yield from syntax (Python 3.3+) delegates to another generator (or any iterable). Instead of manually looping and yielding each value, you write yield from sub_generator().

This is useful for:

  1. Composing generators — one generator delegates part of its work to another
  2. Flattening — yielding all items from nested iterables
  3. Coroutines — in older async code, yield from was used for awaiting (now replaced by await)

It also handles send(), throw(), and return values from sub-generators, making it more than just a shortcut.

Example

python
def inner_gen(n):
    for i in range(n):
        yield i * 2

def outer_gen():
    yield "start"
    yield from inner_gen(3)  # Delegates: 0, 2, 4
    yield from inner_gen(2)  # Delegates: 0, 2
    yield "end"

print(list(outer_gen()))
# ['start', 0, 2, 4, 0, 2, 'end']

# Flattening nested lists
def flatten(nested):
    for item in nested:
        if isinstance(item, list):
            yield from flatten(item)  # Recurse
        else:
            yield item

print(list(flatten([1, [2, [3, 4]], 5])))  # [1, 2, 3, 4, 5]

yield from delegates to a sub-generator, yielding all its values. Great for composing generators and recursive flattening.

Common confusions

  • Confused with: yield

    The difference: yield produces a single value. yield from delegates to an entire sub-generator/iterable, yielding all its values. yield from sub_gen() is equivalent to: for x in sub_gen(): yield x — but also handles send/throw/return.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary