How to Delegate Iteration to a Subgenerator with yield from in Python

Use yield from to delegate iteration from one generator to a subgenerator, flattening nested generator output into a single sequence.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 13 views 0 copies

Python code

15 lines
Python 3.9+
def subgenerator():
    yield "first"
    yield "second"
    yield "third"


def delegate():
    yield "before delegation"
    yield from subgenerator()
    yield "after delegation"


if __name__ == "__main__":
    for item in delegate():
        print(item)

Output

stdout
before delegation
first
second
third
after delegation

How it works

The yield from expression forwards yielded values from the subgenerator to the caller, making the outer generator behave as if its body were spliced into the delegating generator. It also forwards send() and throw() calls, so the delegation is transparent for advanced generator protocols. This pattern reduces nested loops and keeps generator code readable when composing multiple generators.

Common mistakes

  • Using `yield from` with a non-iterable argument instead of a generator/iterable
  • Forgetting that `yield from` can only be used inside a generator function
  • Confusing `yield from` with `return from` — it never returns the subgenerator's value

Variations

  1. Chain multiple generators: `yield from gen1; yield from gen2`
  2. Use `yield from` with lists or other iterables to flatten them into the generator stream

Real-world use cases

  • Composing multiple pipeline stages where each stage is a generator that processes data incrementally.
  • Building a CLI tool that concatenates multiple log files by delegating to per-file parsers.
  • Implementing a recursive generator that yields items from nested tree structures with minimal boilerplate.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.