Sobes.tech
Middle

What must an object have to be an iterator in Python?

sobes.tech AI

Answer from AI

An object is an iterator in Python if it implements two methods:

  • __iter__() — should return the iterator itself (usually return self).
  • __next__() — returns the next element in the sequence, and should raise a StopIteration exception when the end is reached.

Example of a simple iterator:

class CountUpTo:
    def __init__(self, max):
        self.max = max
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.max:
            raise StopIteration
        self.current += 1
        return self.current

counter = CountUpTo(3)
for num in counter:
    print(num)  # Will print 1, 2, 3