Junior — Middle
What is the purpose of the __next__ method in Python iterators?
sobes.tech AI
Answer from AI
The __next__ method in Python iterators is designed to retrieve the next element in a sequence. When next() is called on an iterator, it invokes its __next__ method, which returns the next item. If there are no more items, the method should raise a StopIteration exception to signal the end of iteration.
Example of a simple iterator implementation:
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 number in counter:
print(number) # Will output 1, 2, 3