Google News
logo
Python Program to Create an iterator
To create an iterator in Python, we need to implement the `__iter__()` and `__next__()` methods in a class. The `__iter__()` method returns the iterator object itself.

The `__next__()` method returns the next value from the iterator. Here's an example program that demonstrates how to create an iterator :
Program :
class MyIterator:
    def __init__(self, max_num):
        self.max_num = max_num
        self.current_num = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current_num < self.max_num:
            self.current_num += 1
            return self.current_num
        else:
            raise StopIteration

# create an iterator object
my_iterator = MyIterator(5)

# loop through the iterator
for num in my_iterator:
    print(num)
Output :
1
2
3
4
5
In this example, we define a class called `MyIterator` that implements the `__iter__()` and `__next__()` methods. The `__init__()` method initializes the maximum number of values that can be returned by the iterator and the current number that is being returned.

The `__iter__()` method returns the iterator object itself, and the `__next__()` method returns the next value from the iterator until the maximum number is reached.

When the maximum number is reached, a `StopIteration` exception is raised to indicate that the iterator is done. We create an instance of the `MyIterator` class with a maximum of 5 numbers and then loop through the iterator to print each number.