Making generators with the yield keyword

Making generators with the yield keyword#

Writing iterators is hard. Python makes it easier for you by making it easy to turn a function into a special kind of iterator, called a generator. In principle generators or simple, though there are many nuances that deserve careful attention— read the docs!

Here’s an example generator for the Collatz conjecture:

When you use the yield keyword in a function, Python compiles the function specially so that it will be an iterator. The __next__ method it generates runs your function until the next yield, which provides the next value in the iteration.

There are subtle rules for how yield and return and exceptions interact, particularly because a generator’s return gets translated to a StopIteration exception. If you can, it’s best to avoid mixing yield and return.