Sobes.tech
Junior — Middle

Can you explain how the __next__ method works in Python iterators?

sobes.tech AI

Answer from AI

The __next__ method in Python is a key element of the iterator protocol. It is called to retrieve the next item from the iterator. If there are more items, the method returns the next one; if the items are exhausted, it should raise a StopIteration exception to signal the end of iteration.

Example of a simple iterator:

class Counter:
    def __init__(self, limit):
        self.current = 0
        self.limit = limit

    def __iter__(self):
        return self

    def __next__(self):
        if self.current < self.limit:
            self.current += 1
            return self.current
        else:
            raise StopIteration

for num in Counter(3):
    print(num)  # Will output 1, 2, 3

Thus, __next__ manages sequential access to collection elements or value generation.