Junior — Middle
What is the role and application of an iterator in programming?
sobes.tech AI
Answer from AI
An iterator in programming is an object that allows sequential traversal of elements in a collection (such as a list, set, or dictionary) without needing to know the internal structure of the collection.
In Python, an iterator implements the methods __iter__() and __next__(). When next() is called, the next element is returned, and when the end is reached, a StopIteration exception is raised.
Uses of iterators:
- They allow writing universal code for traversing any collections.
- They are used in
forloops, which automatically invoke the iterator. - They enable creating lazy sequences that generate elements as needed.
Example of creating a custom iterator:
class CountDown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
else:
self.current -= 1
return self.current + 1
for number in CountDown(5):
print(number)
Output:
5
4
3
2
1
Iterators make code more flexible and efficient when working with sequences of data.