Generators are iterators

The alphabet g is a generator object. Generators are, in fact, Python iterators, so we can use the iterator protocol to retrieve – or yield – successive values from the series:

>>> next(g)
1
>>> next(g)
2
>>> next(g)
3

Take note of what happens now that we've yielded the last value from our generator. Subsequent calls to next() raise a StopIteration exception, just like any other Python iterator:

>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

Because generators are iterators, and because iterators must also be iterable, they can be used in all the usual Python constructs which expect iterable objects, such as for-loops:

>>> for v in gen123():
... print(v)
...
1
2
3

Be aware that each call to the generator function returns a new generator object:

>>> h = gen123()
>>> i = gen123()
>>> h
<generator object gen123 at 0x1006eb2d0>
>>> i
<generator object gen123 at 0x1006eb280>
>>> h is i
False

Also note how each generator object can be advanced independently:

>>> next(h)
1
>>> next(h)
2
>>> next(i)
1
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset