Python Iterator
In Python, an iterator is an object that can be iterated or looped upon. It is used to implement the iterator protocol that consists of two methods:
__iter__
: This method returns the iterator object itself. It is used in for and in statements.__next__
: This method returns the next value in the iterator. It raises theStopIteration
exception when there are no more items left to return.
Here's an example of creating an iterator for a list in Python:
class MyIterator: def __init__(self, my_list): self.my_list = my_list self.index = 0 def __iter__(self): return self def __next__(self): if self.index >= len(self.my_list): raise StopIteration else: result = self.my_list[self.index] self.index += 1 return result my_list = [1, 2, 3, 4, 5] my_iter = MyIterator(my_list) for item in my_iter: print(item)
Output:
1 2 3 4 5
In the above example, we created a custom iterator MyIterator
that takes a list as input. The __init__
method initializes the iterator with the list and the __iter__
method returns the iterator object itself. The __next__
method returns the next value in the iterator, and raises the StopIteration
exception when there are no more items left to return.
We then created an instance of MyIterator
with a list [1, 2, 3, 4, 5]
and looped through it using a for
loop. The for
loop calls the __iter__
method to get the iterator object and then calls the __next__
method to get the next value in the iterator. This continues until the StopIteration
exception is raised.