The concept of iterators can be used to create generators. Generators are special iterators, that can be paused and store values. (They use the “yield” directive for this)
The generator can then be resumed to continue operation.
Given is an example of a fibonacci generator with generators. The code can be downloaded from the provided link:
In Python import the module:
>>> import fibonacci as fib
>>> f = fib.generate()
We can generate the 1st 10 numbers in the fibonacci series by:
first_ten = [f.next() for i in range(10)]
Now if we need the next 20 numbers in the series we just resume the function, by re-running it. It remembers from where to start!
next_twenty = [f.next() for i in range(20)]
Generators can really make a program faster, by reducing the processor usage…by generating 1 number at a time.