Sobes.tech
Junior — Middle

How to implement the ability to iterate over the elements of an object as if the object itself were iterable in Python?

sobes.tech AI

Answer from AI

To make an object iterable in Python, you need to implement the __iter__ method, which returns an iterator. An iterator is an object with a __next__ method that returns the next element or raises StopIteration when there are no more elements.

Example of a simple iterable object:

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):
            raise StopIteration
        value = self.data[self.index]
        self.index += 1
        return value

obj = MyIterable([1, 2, 3])
for item in obj:
    print(item)

In this example, the MyIterable object itself is an iterator. You can also make __iter__ return a separate iterator if needed.

Thus, by implementing __iter__ and __next__, the object becomes iterable and supports iteration in for loops.