Junior — Middle
Can you explain the concept of an iterator in Python and how it is used in programming?
sobes.tech AI
Answer from AI
An iterator in Python is an object that allows you to traverse through all the elements of a collection sequentially without needing to know its internal structure.
An iterator implements the iter() and next() methods. When the iter() function is called on a collection, it returns an iterator, and calling next() sequentially returns the elements until the end is reached, after which a StopIteration exception is raised.
Iterators are widely used in for loops, generators, and when working with data streams.
Example:
my_list = [1, 2, 3]
iterator = iter(my_list)
print(next(iterator)) # 1
print(next(iterator)) # 2
print(next(iterator)) # 3
# The next call to next(iterator) will raise StopIteration