
Code
Passing the Torch with yield from
Sometimes a generator wants to hand out every value from another iterable. You could loop:
def both(a, b):
for item in a:
yield item
for item in b:
yield item
...or use yield from, which delegates to the inner iterable until it runs out:
def both(a, b):
yield from a
yield from b
print(list(both([1, 2], "xy"))) # [1, 2, 'x', 'y']
yield from works with any iterable: lists, strings, range, other generators.
It shines when you build generators out of smaller generators, a bit like
snapping pipes together.
Assignment
chain_routes(*routes)yields every stop of every route, in order.list(chain_routes(["a", "b"], ["c"]))is["a", "b", "c"].round_trip(route)yields the route forwards, then walks back to the start without repeating the far end.list(round_trip(["dock", "mill", "tower"]))is["dock", "mill", "tower", "mill", "dock"].
Use yield from in both.
chain_routes(*routes)yields every stop of every route, in order.list(chain_routes(["a", "b"], ["c"]))is["a", "b", "c"].round_trip(route)yields the route forwards, then walks back to the start without repeating the far end.list(round_trip(["dock", "mill", "tower"]))is["dock", "mill", "tower", "mill", "dock"].
Use yield from in both.
main.py Python sleeping
Press Run to try your code, then Check to test it.