What are generators?
A generator, in its simplest form, is a function that returns elements one at a time instead of returning a collection of items. The most important advantage of this is that it requires very little memory and that it doesn't need to have a predefined size. Creating an endless generator (such as the itertools.count
iterator discussed in Chapter 4, Functional Programming – Readability Versus Brevity) is actually quite easy, but it does come with a cost, of course. Not having the size of an object available makes certain patterns difficult to achieve.
The basic trick in writing generators (as functions) is using the yield
statement. Let's use the itertools.count
generator as an example and extend it with a stop
variable:
>>> def count(start=0, step=1, stop=10): ... n = start ... while n <= stop: ... yield n ... n += step >>> for x in count(10, 2.5, 20): ... print(x) 10 12.5 15.0 17.5 20.0
Due to the potentially infinite nature...