How iteration works in Python
In Python, an iterator is an object that represents a stream of data. While iterators are available for containers, sequences in particular always support iteration.
Iterators have the __next__()
method available (or the built-in next()
function). Calling next()
multiple times returns successive items from the data stream. When no more items are available, a StopIteration
exception is thrown.
Any class can use an iterator by defining a container.__iter__()
method. This method returns an iterator object, typically just self
. This object is necessary to support the iterator protocol. Different types of iteration can be supported, with each one providing a specific iterator request. For example, a tree structure could support both breadth-first and depth-first traversals.
The iterator protocol mentioned previously actually comprises two methods: iterator.__next__()
and iterator.__iter__()
. (Notice that __iter__()
has a different class compared to the one above.)
As...