Delegate Iteration with yield from
Core idea
Inside a generator, yield from source delegates to an iterable. The caller receives the source items in order; when the source ends, the outer generator continues. For ordinary item traversal, it resembles a for loop with yield. With subgenerators, delegation also supports control operations and captures a completion value, explained in the following lessons.
def batches(): yield from [1, 2] yield from (3, 4)print(list(batches()))Items are yielded individually, not as two collections.
Delegate to a generator
def labels(): yield "A" yield "B"def manifest(): yield "start" yield from labels() yield "end"print(list(manifest()))After the inner generator ends, the outer generator resumes.
Handle an empty batch
def flatten(groups): for group in groups: yield from groupprint(list(flatten([[5], [], [6, 7]])))The empty iterable yields nothing and does not stop the outer loop.
Common mistake
yield group emits the group itself; yield from group emits its members. Delegation is not recursive flattening and strings yield individual characters.
Practice
Write a generator that delegates to three batches, including an empty one. Compare its output with yield group.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Yield from delegation
Check your understanding of yield from.
What is printed?
def items(): yield from [1, 2] yield 3print(list(items()))What is printed?
def items(): yield from [] yield 8print(list(items()))What is printed?
def items(): yield from "ab"print(list(items()))Does yield from recursively flatten arbitrary nested iterables?