Revision 1 as of 2005-04-02 23:58:27

Clear message

An iterator is an object that implements __iter__ and and next.

You can use them in for loops, and you can use them to construct lists.

Example Iterator

Here is an iterator that returns a random number of 1's:

   1 import random
   2 
   3 class RandomIterator:
   4     def __iter__(self):
   5         return self
   6     def next(self):
   7         if random.choice(["go", "go", "stop"]) == "stop":
   8             raise StopIteration  # signals "the end"
   9         return 1

Q: Why is __iter__ there, if it just returns self?

A: This is so that the iterator can be used in a for...in loop.

   1 for eggs in RandomIterator():
   2     print eggs

You can also use it in list construction:

   1 >>> list(RandomIterator())
   2 [1]
   3 >>> list(RandomIterator())
   4 []
   5 >>> list(RandomIterator())
   6 [1, 1, 1, 1, 1]
   7 >>> list(RandomIterator())
   8 [1]

...both of these uses require __iter__.

An object isn't an iterator unless it provides both methods. If it does provide these methods, then it's an iterator.

See also: ["Generators"]

Discussion

Unable to edit the page? See the FrontPage for instructions.