Sobes.tech
Junior — Middle

What is the result of the __iter__ method in Python?

sobes.tech AI

Answer from AI

The __iter__ method in Python returns an iterator object. This iterator must implement the __next__ method, which returns the next element of the sequence each time it is called, and raises a StopIteration exception when the end is reached.

Thus, calling iter(obj) invokes obj.__iter__(), and the returned object is used in for loops and other constructs that work with iterators.

Example:

class MyRange:
    def __init__(self, n):
        self.n = n
    def __iter__(self):
        self.current = 0
        return self
    def __next__(self):
        if self.current < self.n:
            val = self.current
            self.current += 1
            return val
        else:
            raise StopIteration

for i in MyRange(3):
    print(i)
# Output:
# 0
# 1
# 2