Sobes.tech
Junior — Middle

How to implement a mechanism for traversing collection elements using an iterator?

sobes.tech AI

Answer from AI

In Python, an iterator is an object that implements the __iter__() and __next__() methods. To implement a mechanism for traversing elements of a collection using an iterator, you need to create an iterator class that maintains the traversal state and returns the next element when __next__() is called.

Example of an iterator implementation for a list:

class MyIterator:
    def __init__(self, collection):
        self.collection = collection
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.index < len(self.collection):
            item = self.collection[self.index]
            self.index += 1
            return item
        else:
            raise StopIteration

Usage:

my_list = [1, 2, 3]
iterator = MyIterator(my_list)
for item in iterator:
    print(item)

Such an iterator can be used in for loops and other constructs that expect an iterator.