Generators provide an elegant way to write simple and efficient code for functions that return a sequence of elements. Based on the yield statement, they allow you to pause a function and return an intermediate result. The function saves its execution context and can be resumed later, if necessary.
For instance, the function that returns consecutive numbers of the Fibonacci sequence can be written using a generator syntax. The following code is an example that was taken from the PEP 255 (Simple Generators) document:
def fibonacci(): a, b = 0, 1 while True: yield b a, b = b, a + b
You can retrieve new values from generators as if they were iterators, so using the next() function or for loops:
>>> fib = fibonacci() ...