Junior — Middle
What functions should an object implement to be traversed using the 'in' loop in Python?
sobes.tech AI
Answer from AI
For an object to be iterable with a for ... in loop in Python, it must implement the iteration protocol. This means the object must have an __iter__() method that returns an iterator.
The iterator, in turn, must implement the __next__() method, which returns the next element in the sequence and raises a StopIteration exception when the sequence ends.
Example:
class MyIterable:
def __init__(self, data):
self.data = data
def __iter__(self):
self.index = 0
return self
def __next__(self):
if self.index < len(self.data):
result = self.data[self.index]
self.index += 1
return result
else:
raise StopIteration
obj = MyIterable([1, 2, 3])
for item in obj:
print(item)
Thus, having __iter__() and __next__() methods allows an object to be iterable.