Sobes.tech
Junior — Middle

What is the purpose of objects that implement the iteration interface?

sobes.tech AI

Answer from AI

Objects that implement the iteration interface in Python are designed for sequentially traversing elements of collections or other data structures without needing to know the internal workings of the object.

The iteration interface includes the methods __iter__() and __next__(). An iterator object returns the next element when next() is called and signals the end of the sequence by raising a StopIteration exception.

This allows such objects to be used in for loops, generators, and other constructs that work with iterators.

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:
            self.current += 1
            return self.current
        else:
            raise StopIteration

for number in CountUpTo(5):
    print(number)

Here, the CountUpTo object allows iteration over numbers from 1 to 5.