As of Python 2.2, Python supports iteration over containers. To affect this, one may use one of two distinct methods. Sequences always support iteration methods. The purpose of iterators is to allow user-defined classes to support iteration.
The __iter__() method is needed to be defined for container objects to provide iteration support:
- __iter__(): Returns an iterator object. This object is required to support the iterator protocol (described below). If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (For example, a tree structure may support multiple forms of iteration: both breadth-first and depth-first traversal.)
The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:
- __iter__(): Returns the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements.
- next(): Returns the next item from the container. If there are no further items, it raises the StopIteration exception.
Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol.
The intention of the protocol is that once an iterator's next() method raises StopIteration, it will continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken.
Python's generators provide a convenient way to implement the iterator protocol. If a container object's __iter__() method is implemented as a generator, it will automatically return an iterator object (properly called a generator object). This object supplies the __iter__() and next() methods.
C programmers should note that the iterator protocol corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.