Despite reading up on it, I still dont quite understand how __iter__
works. What would be a simple explaination?
I\'ve seen def__iter__(self): retu
In Python, an iterator is any object that supports the iterator protocol. Part of that protocol is that the object must have an __iter__()
method that returns the iterator object. I suppose this gives you some flexibility so that an object can pass on the iterator responsibilities to an internal class, or create some special object. In any case, the __iter__()
method usually has only one line and that line is often simply return self
The other part of the protocol is the next()
method, and this is where the real work is done. This method has to figure out or create or get the next thing, and return it. It may need to keep track of where it is so that the next time it is called, it really does return the next thing.
Once you have an object that returns the next thing in a sequence, you can collapse a for loop that looks like this:
myname = "Fredericus"
x = []
for i in [1,2,3,4,5,6,7,8,9,10]:
x.append(myname[i-1])
i = i + 1 # get the next i
print x
into this:
myname = "Fredericus"
x = [myname[i] for i in range(10)]
print x
Notice that there is nowhere where we have code that gets the next value of i because range(10) is an object that FOLLOWS the iterator protocol, and the list comprehension is a construct that USES the iterator protocol.
You can also USE the iterator protocol directly. For instance, when writing scripts to process CSV files, I often write this:
mydata = csv.reader(open('stuff.csv')
mydata.next()
for row in mydata:
# do something with the row.
I am using the iterator directly by calling next()
to skip the header row, then using it indirectly via the builtin in
operator in the for
statement.