Sobes.tech
Junior — Middle

Explain the concept of an iterator in Python and how it is used to traverse data collections.

sobes.tech AI

Answer from AI

An iterator in Python is an object that implements the __next__() method and returns the next element of a sequence each time it is called. Iterators allow traversing data collections (lists, tuples, dictionaries, etc.) one element at a time without needing to load the entire collection into memory.

Iterators are used in for loops and can also be created manually using the iter() function.

Example of using an iterator:

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

print(next(iterator))  # 1
print(next(iterator))  # 2
print(next(iterator))  # 3

If next() is called after the elements are exhausted, a StopIteration exception is raised, signaling the end of the iteration.

Iterators are useful for processing large or infinite data streams, allowing for step-by-step handling.