Skip to main content

AD

Iterator

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]
            self.index += 1
            return item
        else:
            raise StopIteration

# Creating an iterator object
my_iterator = MyIterator([1, 2, 3, 4, 5])

# Using the iterator
for item in my_iterator:
    print(item)


Output:

1
2
3
4
5


In this example:
- We define a custom iterator MyIterator that takes a list as input.
- The __iter__() method returns the iterator object itself.
- The __next__() method fetches the next item in the list. It starts from the beginning of the list ("index = 0") and increments the index by 1 in each iteration.
- When there are no more elements to return ("index" exceeds the length of the list), "StopIteration" is raised to signal the end of iteration.
- We create an instance of "MyIterator" with a list [1, 2, 3, 4, 5] and iterate over it using a "for" loop.

Iterators are widely used in Python for looping over sequences and processing large data sets efficiently. They are also an essential part of Python's iteration protocol, which allows custom objects to be used in constructs like "for" loops, comprehensions, and generator expressions.

Comments