Home » Learn Python » Iterators » Creating an Iterator

Creating an Iterator

Iterators in Python are objects that you can retrieve other objects from, one by one. For example, you can loop over them using for … in.

To turn a class into an iterator, you have to implement the __iter__ and __next__ dunder methods.

To stop iteration you raise StopIteration.

To create an iterator:

  • Implement __iter__. This will get called once every time before you begin to iterate. It must return a reference to self.
  • Implement __next__. This needs to return the objects you will retrieve via iteration.
  • Raise StopIteration when you want to stop iterating.

Iterator Example

class NumberGenerator:

    def __iter__(self):
        self._current = 0
        return self

    def __next__(self):
        self._current += 1

        if self._current > 5:
            raise StopIteration
        
        return self._current

numbers = NumberGenerator()

for x in numbers:
    print(x)
1
2
3
4
5

Leave a Reply

Blog at WordPress.com.

%d