Chain Generators with yield from in Python

Combine multiple generators into one seamless sequence using the `yield from` delegation syntax in Python.

Easy Python 3.3+ Aug 9, 2026 Functions & basics 14 views 0 copies

Python code

16 lines
Python 3.3+
def numbers():
    yield 1
    yield 2
    yield 3

def letters():
    yield 'a'
    yield 'b'
    yield 'c'

def combined():
    yield from numbers()
    yield from letters()

if __name__ == "__main__":
    print(list(combined()))

Output

stdout
[1, 2, 3, 'a', 'b', 'c']

How it works

yield from delegates the iteration of an inner generator to the outer one. This allows you to flatten nested generators without explicit loops. It also forwards exceptions and return values from the inner generator. This pattern keeps the code clean and avoids manually iterating and yielding each item.

Common mistakes

  • Confusing `yield from` with `return from` (not a thing).
  • Expecting `yield from` to work with non-generator iterables (it does, but usually you use `yield from iterable`).
  • Forgetting that `yield from` only works inside generator functions.

Variations

  1. Use `itertools.chain(numbers(), letters())` to chain iterables without custom generators.
  2. Use a generator expression with nested loops if the inner iterables are known.

Real-world use cases

  • Combining multiple data sources (e.g., reading multiple CSV files) into a single stream for processing.
  • Building a lazy pipeline where each stage yields results, and `yield from` composes them.
  • Delegating to sub-generators in recursive generators, like traversing a tree or nested structures.

Sponsored

Run this sample

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

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.