June 2017
Beginner
352 pages
8h 39m
English
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)...123
Be aware that ...
Read now
Unlock full access