Junior
What should the `next` method contain to implement iteration?
sobes.tech AI
Answer from AI
The next method (or __next__ in Python 3) should:
- Return the next item in the iteration.
- Raise a
StopIterationexception when there are no more items.
// Example implementation of the __next__ method for a simple iterator
class MyIterator:
def __init__(self, data):
self.data = data
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.data):
raise StopIteration // Exception at the end of iteration
value = self.data[self.index]
self.index += 1
return value // Return the next element