Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

In Python, to iterate over elements of a collection using an iterator, you can use the built-in iterator mechanism. Any object that supports the iterator protocol has the methods __iter__() and __next__().

Example of iterating over a collection with an iterator:

my_list = [1, 2, 3]
iterator = iter(my_list)  # Get an iterator

while True:
    try:
        element = next(iterator)  # Get the next element
        print(element)
    except StopIteration:
        break  # Iteration is complete

You can also typically iterate over a collection using a for loop, which automatically uses the iterator:

for element in my_list:
    print(element)

If you want to implement your own iterator, you need to define the __iter__() and __next__() methods in your class.