An iterator
is nothing more than a container object that implements the iterator protocol. It is based on two methods:
Iterators can be created with a sequence using the iter
built-in function, for example:
>>> i = iter('abc') >>> i.next() 'a' >>> i.next() 'b' >>> i.next() 'c' >>> i.next() Traceback (most recent call last): File "<stdin>", 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 to stop cycling. To create a custom iterator, a class with a next
method can be written, as long as it provides the special method __iter__
that returns an instance of the iterator:
>>> class MyIterator(object): ... def __init__(self, step): ... self.step = step ... def next(self...