Python - Build a Basic Python Iterator

Today I am going to explain How would one create an iterative function (or iterator object) in python?

Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__() and next(). The __iter__ returns the iterator object and is implicitly called at the start of loops. The next() method returns the next value and is implicitly called at each loop increment. next() raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.

Here's a simple example of a counter:

class Counter:
   def __init__(self, low, high):
       self.current = low
       self.high = high

   def __iter__(self):
       return self

   def next(self):
       if self.current > self.high:
           raise StopIteration
           self.current += 1
           return self.current - 1

for c in Counter(3, 8):
   print c
This will print:

This is easier to write using a generator, as covered in a previous answer:

def counter(low, high):
   current = low
   while current <= high:
       yield current
       current += 1

for c in counter(3, 8):
   print c

The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter. David Mertz's article, Iterators and Simple Generators, is a pretty good introduction.

Leave a comment