Junior
What is the purpose of the iter method in Python?
sobes.tech AI
Answer from AI
The __iter__ method in Python is responsible for returning an iterator for an object. If an object has this method, it is considered iterable. The iterator returned by __iter__ must implement the __next__ method, which returns the next element in the container or raises a StopIteration exception when there are no more elements.
Example:
class MyCollection:
def __init__(self, data):
self.data = data
def __iter__(self): # Returns an iterator for the class instance
return iter(self.data)
# Using the iterator:
collection = MyCollection([1, 2, 3])
iterator = iter(collection) # Calls collection.__iter__()
print(next(iterator)) # Calls iterator.__next__() -> 1
print(next(iterator)) # Calls iterator.__next__() -> 2
print(next(iterator)) # Calls iterator.__next__() -> 3
try:
print(next(iterator))
except StopIteration:
print("Iteration stopped.")
# The for loop implicitly uses __iter__ and __next__:
print("Using for loop:")
for item in collection: # First calls collection.__iter__(), then iteratively next()
print(item)
Thus, __iter__ is key to supporting the iteration protocol in Python.