yield from and Delegation
Compose generators.
The Problem yield from Solves
When one generator wants to yield every value from another iterable, you can write a manual loop. yield from does the same thing in one line.
def manual():
for x in [1, 2, 3]:
yield x
print(list(manual()))Introducing yield from
yield from iterable delegates to that iterable, yielding each of its values in turn. It is shorter and clearer than a forwarding loop.
def delegate():
yield from [1, 2, 3]
print(list(delegate()))All lessons in this course
- The Iterator Protocol
- Generator Functions
- Generator Expressions
- yield from and Delegation