Junior — Middle
Explain the concept of an iterator and how it is used when traversing data collections.
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 Python, iterators implement the __iter__() and __next__() methods. When we use a for loop, Python automatically calls these methods to get the next element.
Example of using an iterator:
my_list = [1, 2, 3]
iterator = iter(my_list) # Get an iterator
print(next(iterator)) # 1
print(next(iterator)) # 2
print(next(iterator)) # 3
# The next call to next(iterator) will raise a StopIteration exception
Iterators are useful because they allow working with large or even infinite sequences, loading elements one by one, saving memory, and simplifying collection traversal code.