- publishing free software manuals
An Introduction to Python
by Guido van Rossum and Fred L. Drake, Jr.
Paperback (6"x9"), 124 pages
ISBN 0954161769
RRP £12.95 ($19.95)

Sales of this book support the Python Software Foundation! Get a printed copy>>>

9.9 Iterators

By now you have probably noticed that most container objects can be looped over using a for statement:

    for element in [1, 2, 3]:
        print element
    for element in (1, 2, 3):
        print element
    for key in {'one':1, 'two':2}:
        print key
    for char in "123":
        print char
    for line in open("myfile.txt"):
        print line

This style of access is clear, concise, and convenient. The use of iterators pervades and unifies Python. Behind the scenes, the for statement calls iter() on the container object. The function returns an iterator object that defines the method next() which accesses elements in the container one at a time. When there are no more elements, next() raises a StopIteration exception which tells the for loop to terminate. This example shows how it all works:

    >>> s = 'abc'
    >>> it = iter(s)
    >>> it
    <iterator object at 0x00A1DB50>
    >>> it.next()
    >>> it.next()
    >>> it.next()
    >>> it.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?

Having seen the mechanics behind the iterator protocol, it is easy to add iterator behavior to your classes. Define a __iter__() method which returns an object with a next() method. If the class defines next(), then __iter__() can just return self:

    class Reverse:
        "Iterator for looping over a sequence backwards"
        def __init__(self, data):
            self.data = data
            self.index = len(data)
        def __iter__(self):
            return self
        def next(self):
            if self.index == 0:
                raise StopIteration
            self.index = self.index - 1
            return self.data[self.index]
    >>> for char in Reverse('spam'):
    ...     print char
ISBN 0954161769An Introduction to PythonSee the print edition