Menu Close

Articles

Python: generator

The generator is a special function that do not terminate after returning a result. Instead it’s instance is suspended in memory for a while until the last result is created. Think about it like a resumable function.

Example:

In this example we create a function that generate integer numbers:

Homework: Open this example live and run it: generator

This will print:

test_generator

The function generator is test_generator(). This is a resumable function that will stay in memory and wait for next() to be invoked. When the last element is generated the function terminate. A generator function is a “high order function” and must be instantiated with a parameter.

aindex

I have created 2 generators using the same function. First generator “aindex” is used into a loop like an iterable collection. Not all values are generated in memory but one by one. This is very efficient.

bindex

Second generator bindex = test_generator(3).For this generator I have used next(bindex) to create 2 values (0, 1). Evert time next() is invoked a new value is created. The third value is never used therefore “bindex” generator do not reach the end until program termination.

Keyword yield

Keyword yield is specific to generators. This is like return, except the function do not terminate. Instead the execution is suspended and resumed using next(). This construct is very common in Python and is used for performance.

Read next: Criticism of Python