Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Iterator: a counter

  • StopIteration
  • next
  • iter
  • next

We can create a iterator using a class. We are required to implement the __iter__ method that returns the iterator object and the __next__ method that returns the next element in our iteration. We can indicated that the iteration was exhaused by raising a StopIteration exception.

The instance-object that is created from this class-object is the iterator, not the class-object itself!

  • __iter__
  • __next__ (in Python 2 this used to called next)
  • raise StopIteration
class Counter():
   def __init__(self):
       self.count = 0

   def __iter__(self):
       return self

   def __next__(self):
       self.count += 1
       if self.count > 3:
           raise StopIteration
       return self.count