In Python, an iterator is an object that allows you to traverse through a collection of elements, such as lists, tuples, or dictionaries, one at a time. Iterators provide a way to access elements sequentially without needing to know the underlying implementation of the data structure. An iterator must implement two methods: 1. __iter__(): This method returns the iterator object itself. It is called when you use the `iter()` function on the iterator. 2. __next__() : This method returns the next item in the iterator. It is called repeatedly to fetch the next element in the sequence. When there are no more elements to return, it raises the ' StopIteration ' exception. Here's an example to illustrate how iterators work: class MyIterator: def __init__(self, data): self.data = data self.index = 0 def __iter__(self): return self def __next__(self): if self.index < len(self.data): item = self.data[self.index]
Small & Important