Sobes.tech
Junior — Middle

What functions does the Iterator class provide for traversing a collection?

sobes.tech AI

Answer from AI

The Iterator class in Python provides basic functions for sequential traversal of collection elements:

  • __iter__() — returns the iterator itself, allowing it to be used in for loops.
  • __next__() — returns the next element of the collection. When the end of the collection is reached, it raises a StopIteration exception.

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 StopIteration

Thus, an iterator allows traversing a collection element by element without needing to know its internal structure.