Middle
What methods are available for an iterator in Python?
sobes.tech AI
Answer from AI
In Python, an iterator has two main methods:
__iter__(): Returns the iterator object itself. This is part of the iteration protocol.__next__(): Returns the next item from the iteration. When there are no more items, it raises aStopIterationexception.
Example:
class MyIterator:
def __init__(self, data):
self.data = data
self.index = 0 # Index to track the current position
def __iter__(self):
return self # The __iter__ method returns the iterator itself
def __next__(self):
if self.index < len(self.data):
value = self.data[self.index]
self.index += 1
return value # Return the next element
else:
raise StopIteration # Raise exception when iteration ends
# Using the iterator
my_list = [10, 20, 30, 40]
my_iter = MyIterator(my_list)
# Iteration using next()
print(next(my_iter)) # 10
print(next(my_iter)) # 20
# Iteration using a for loop (which internally uses __iter__ and __next__)
for item in MyIterator(my_list):
print(item) # 10, 20, 30, 40