The yield from expression

Another interesting construct is the yield from expression. This expression allows you to yield values from a sub iterator. Its use allows for quite advanced patterns, so let's just see a very quick example of it:

# gen.yield.for.py
def print_squares(start, end):
for n in range(start, end):
yield n ** 2

for n in print_squares(2, 5):
print(n)

The previous code prints the numbers 4, 9, 16 on the console (on separate lines). By now, I expect you to be able to understand it by yourself, but let's quickly recap what happens. The for loop outside the function gets an iterator from print_squares(2, 5) and calls next on it until iteration is over. Every time the generator is called, execution is suspended (and later resumed) on yield n ** 2, which returns the square of the current n. Let's see how we can transform this code benefiting from the yield from expression:

# gen.yield.from.py
def print_squares(start, end):
yield from (n ** 2 for n in range(start, end))

for n in print_squares(2, 5):
print(n)

This code produces the same result, but as you can see yield from is actually running a sub iterator, (n ** 2 ...). The yield from expression returns to the caller each value the sub iterator is producing. It's shorter and it reads better.