Iterators & Generators
yield from
Delegating to sub-generators with yield from — simplifying nested iteration, bidirectional communication, and building recursive generators.
Interview: Advanced generator pattern — shows deep understanding of Python generator mechanics.
yield from (Python 3.3+) delegates to a sub-generator, transparently forwarding all values, sends, and exceptions. It replaces the boilerplate of iterating over a sub-generator and yielding each value individually.
Basic Usage
yield from iterable— yields all items from the iterable one by one- Works with any iterable, not just generators — lists, ranges, strings, etc.
- Replaces the pattern:
for item in sub: yield item
Bidirectional Communication
yield fromtransparently forwardssend()andthrow()to the sub-generator- The return value of the sub-generator becomes the result of the
yield fromexpression - This enables coroutines to compose and communicate in complex ways
Recursive Generators
yield from is essential for recursive generators, especially tree traversal:
- Tree traversal — yield from left subtree, yield current, yield from right subtree
- Flattening nested structures — recursively yield from sub-lists
- Without yield from, recursive generators need explicit for loops
Interview Insight
Know when to use yield from vs a for loop. yield from is cleaner and properly forwards send/throw/close to the sub-generator — important for coroutine composition.
Use Cases
Tree traversal — in-order, pre-order, post-order traversal of binary trees
Flattening nested structures — lists of lists, nested dicts
Coroutine composition — chaining generators with bidirectional communication
Parser combinators — delegating to sub-parsers
Graph algorithms — DFS/BFS traversal with generator-based exploration
Common Mistakes
Forgetting that yield from captures the sub-generator return value
Using yield from with a non-iterable — raises TypeError
Not understanding that send/throw/close are forwarded to the sub-generator
Using for loop + yield instead of yield from — works but misses send/throw forwarding
Infinite recursion in recursive generators — must have a base case