Generators

yield from and chaining generators

When one generator wants to hand off to another iterable, writing a for loop with yield works but feels noisy. yield from does the same thing in one line.


A common pattern is one generator that wants to forward every value of another iterable.

You can do that with a plain loop and yield, but the loop is just plumbing:

Python
Output

yield from does the exact same thing in one line:

Python
Output

The keyword takes any iterable: a list, a string, a generator, anything you can loop over.

Python

Forwarding a list works just as well:

Python
Output

And forwarding another generator:

Python
Output

What will be the output?

Python

You can chain several generators by stacking yield from statements:

Python
Output

What will be the output?

Python

A small wrapper that delegates to range() becomes a one-liner:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python