What is a generator?

A generator is a special kind of function that returns an iterator. It looks like a normal function, but values are returned to the caller using a yield statement instead of a return statement. When yield is called, the function is suspended and the yielded value is returned to the caller. The function is then resumed again the next time the caller asks for another value.

Generators are most often used with for-in and other operations that are designed to work with iterables:

>>> def gen():
...     yield 1
...     yield 2
...     for each in (3,4,5):
.