Sobes.tech
Junior — Middle

Can you explain the principle of how an iterator works in programming?

sobes.tech AI

Answer from AI

An iterator is an object that allows sequential traversal of the elements of a collection without exposing its internal structure. In programming, an iterator provides methods to access the next element and to check if there are more elements.

In Python, an iterator implements the __iter__() and __next__() methods. When you use a for loop, Python automatically calls these methods to retrieve elements sequentially.

Example of a simple iterator in Python:

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)

This code will output numbers from 1 to 5. An iterator allows abstraction from the data structure and sequentially retrieves elements.