How Python interprets a for loop

The loop in the following code:
for element in collection:
    # ...
    # do something with element
    # ...
Is essentially translated by the compiler to:
collection_iter = iter(collection)
while True:
    try:
        element = collection_iter.next()
    except StopIteration:
        break
    # ...
    # do something with element
    # ...

What is this iter() function?

It calls the __iter__() method of its argument. This method should return an object that implements the iterator protocol.

The iterator protocol

From http://docs.python.org/release/2.5/lib/typeiter.html

A sample iterator - a counter

Definition

class counter (object):
    def __init__ (self, start=0, stop=None, by=1):
        self._value = start
        self._stop = stop
        self._by = by

    def __iter__ (self):
        return self

    def next (self):
        val = self._value
        if self._stop is not None and val >= self._stop:
            raise StopIteration
        self._value += self._by
        return val

Usage

cntr = counter(0, 10)
cntr.next() # 0
cntr.next() # 1
for n in cntr:
    print n,
# prints 2 3 4 5 6 7 8 9
Let's talk about special methods