Sobes.tech
Junior — Middle

How is the iteration mechanism over objects implemented in Python?

sobes.tech AI

Answer from AI

In Python, the iteration mechanism is implemented through the iterator protocol, which includes two methods: __iter__() and __next__().

  • An object is considered iterable if it has a __iter__() method that returns an iterator.
  • An iterator is an object with a __next__() method that returns the next element in the sequence each time it is called, or raises a StopIteration exception when the elements are exhausted.

Example of implementing a custom iterator:

class CountUpTo:
    def __init__(self, max):
        self.max = max
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current < self.max:
            self.current += 1
            return self.current
        else:
            raise StopIteration

for number in CountUpTo(5):
    print(number)

Thus, the for loop automatically calls __iter__() and then repeatedly calls __next__() to get the elements.