December 2018
Beginner to intermediate
796 pages
19h 54m
English
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.pydef print_squares(start, end): for n in range(start, end): yield n ** 2for 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) ...
Read now
Unlock full access