April 2019
Intermediate to advanced
646 pages
16h 48m
English
An iterator is nothing more than a container object that implements the iterator protocol. This protocol consists of two methods:
Iterators can be created from a sequence using the iter built-in function. Consider the following example:
>>> i = iter('abc')
>>> next(i)
'a'
>>> next(i)
'b'
>>> next(i)
'c'
>>> next(i)
Traceback (most recent call last):
File "<input>", line 1, in <module>
StopIteration
When the sequence is exhausted, a StopIteration exception is raised. It makes iterators compatible with loops, since they catch this exception as a signal to end the iteration. If you create a custom iterator, you need to provide objects ...