The for statement in Python operates on iterators. Objects are iterable (an interface) if they have an iter method that returns an iterator. Iterable objects can be the value of the
for <name> in <expression>:
<suite>
To execute a for statement, Python evaluates the header
>>> counts = [1, 2, 3]
>>> for item in counts:
print(item)
1
2
3
In the above example, the counts list returns an iterator from its iter() method. The for statement then calls that iterator’s next() method repeatedly, and assigns the returned value to item each time. This process continues until the iterator raises a StopIteration exception, at which point execution of the for statement concludes.
With our knowledge of iterators, we can implement the execution rule of a for statement in terms of while, assignment, and try statements.
>>> items = counts.__iter__()
>>> try:
while True:
item = items.__next__()
print(item)
except StopIteration:
pass
1
2
3
Above, the iterator returned by invoking the iter method of counts is bound to a name items so that it can be queried for each element in turn. The handling clause for the StopIteration exception does nothing, but handling the exception provides a control mechanism for exiting the while loop.
To use an iterator in a for loop, the iterator must also have an iter method. The Iterator types http://docs.python.org/3/library/stdtypes.html#iterator-types _ section of the Python docs suggest that an iterator have an ``__iter__
method that returns the iterator itself, so that all iterators are iterable.