Chain Generators with yield from in Python
Combine multiple generators into one seamless sequence using the `yield from` delegation syntax in Python.
Python code
16 linesdef 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
[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
- Use `itertools.chain(numbers(), letters())` to chain iterables without custom generators.
- 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
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.