Iterator

Iterator#

An iterator is an object that implements the iterator protocol.

The iterator protocol suggests that an object have the following:

  • The __iter__ dunder that returns object with a __next__ dunder.

  • The __next__ dunder is supposed to return the elements of the iterator one by one and raise a StopIteration exception when there are no more elements to iterate.

Defining iterator#

You can create your own iterators by simply implementing teh iterator protocol. These classes’ instances can be used wherever regular python iterators can be used, e.g., in a list.


The following code defines the MyIterator, which allows you to iterate len times. Each iteration will return a random value between 0 and 100.

from random import randint


class MyIterator:
    def __init__(self, len: int):
        self.len = len
        self.state = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.state < self.len:
            self.state += 1
            return randint(0, 100)
        else:
            raise StopIteration()

The following cell demonstrates the use of the MyIterator in a for loop.

[i for i in MyIterator(10)]
[37, 89, 62, 7, 51, 8, 11, 11, 99, 30]

It returned exactly len values, which seem to be random.