Sobes.tech
Junior — Middle

Can you explain what an iteration protocol is and what it is used for in programming?

sobes.tech AI

Answer from AI

An iteration protocol in programming is an agreement that allows objects to be iterable in loops, for example, in Python using for. An object implementing the iteration protocol must provide an __iter__() method that returns an iterator, and the iterator must have a __next__() method that returns the next element or raises a StopIteration exception when the elements are exhausted.

This is used for convenient and efficient traversal of data collections, generators, and other sequences without needing to know the internal structure of the object.

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)