Sobes.tech
Junior — Middle

Can you explain what an iterator protocol is and how it is used in programming?

sobes.tech AI

Answer from AI

An iterator protocol in programming is a convention that defines how an object should provide sequential access to its elements. In Python, an iterator is an object that implements the __iter__() and __next__() methods.

  • The __iter__() method returns the iterator itself.
  • The __next__() method returns the next element in the sequence or raises a StopIteration exception if there are no more elements.

This allows objects to be used in for loops and other iteration constructs.

Example of a simple iterator in Python:

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)