How to build a basic Python iterator?

Estimated read time 2 min read

In Python, an iterator is an object that implements the iterator protocol, which consists of the __iter__() and __next__() methods. The __iter__() method returns the iterator object itself, and the __next__() method returns the next value in the sequence. When there are no more items to be returned, the __next__() method raises the StopIteration exception to signal the end of the iteration.

Here’s an example of a basic Python iterator that generates a sequence of numbers from 1 to a specified limit:

class NumberIterator:
    def __init__(self, limit):
        self.limit = limit
        self.current = 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= self.limit:
            value = self.current
            self.current += 1
            return value
        else:
            raise StopIteration

# Usage
num_iterator = NumberIterator(5)
for num in num_iterator:
    print(num)

In this example, we define a NumberIterator class that implements the iterator protocol. The __init__() method initializes the iterator with a limit value, and the current attribute keeps track of the current value in the sequence. The __iter__() method returns the iterator object itself, and the __next__() method generates the next value in the sequence until the limit is reached. When there are no more items to be returned, the __next__() method raises the StopIteration exception. The iterator can be used in a for loop to iterate over the values in the sequence, as shown in the usage example.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply