Generators and yield
Not met yet
A function with yield in it is a generator function. Calling it runs none of the body: it hands back a generator, which is an iterator. Each next() runs the body as far as the next yield, hands that value over and pauses there, with its variables kept. When the body reaches the end, the generator is finished, and looping over it again gives nothing.
Try it
main.pyOutput
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks calling a generator function runs its body straight away.
- Thinks next() runs the whole generator body rather than stopping at the next yield.
- Thinks yield ends the function like return, or writes return where yield is needed, so only one value comes out.
- Thinks a used-up iterator or generator starts again from the beginning when it is looped over a second time.