61. Iterator Protocol

In Python, the iterator protocol consists of two main methods: __iter__() and __next__(). These methods allow you to create custom iterators, enabling you to iterate over an object. Here's a detailed explanation and examples of how to implement a custom iterator.

1. Basic Custom Iterator

To create a basic custom iterator, you need to define a class that implements both __iter__() and __next__() methods. The __iter__() method returns the iterator object itself, while __next__() returns the next value in the iteration.

class Countdown:
    def __init__(self, start):
        self.start = start

    def __iter__(self):
        self.current = self.start
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current

# Using the iterator
countdown = Countdown(5)
for num in countdown:
    print(num)

Output:

In this example, the Countdown class counts down from a starting number. The __next__() method decreases the current value until it reaches 0, at which point it raises StopIteration to signal the end of the iteration.


2. Custom Range Class

You can implement your own version of the range function using the iterator protocol. This will give you control over the iteration behavior.

Output:

Here, MyRange implements a custom range where you can specify a start and end value. The __next__() method increments the current value and returns it until the current value reaches or exceeds the end value.


3. Fibonacci Iterator

A Fibonacci sequence iterator is another good example of using the iterator protocol.

Output:

This example shows a Fibonacci sequence generator, where each call to __next__() produces the next Fibonacci number in the sequence until the specified limit is reached.


4. Iterating Over Multiple Items

If you want to iterate over multiple items or collections, you can customize the iteration logic by combining the __iter__() and __next__() methods.

Output:

In this example, MultiIterator takes multiple iterables (lists) and iterates through them sequentially. Each time __next__() is called, it retrieves the next value from each iterable in turn.


5. Custom Infinite Iterator

You can implement an iterator that doesn't stop, such as one that generates an infinite sequence of numbers.

Output:

This InfiniteCounter iterator will keep generating numbers starting from the specified value. It never stops, but we limit the number of iterations to 5 in this example.


6. Iterator for File Lines

You can create a custom iterator for reading lines from a file.

This custom iterator reads lines from a file one at a time. When all lines have been read, it raises StopIteration.


7. Prime Numbers Iterator

Here is an example of an iterator that generates prime numbers.

Output:

This example shows a prime number generator that continuously checks for prime numbers, starting from 2.


8. Custom Iterator with Reset

You can implement an iterator that allows resetting the iteration state.

Output:

This example shows an iterator that can be reset to the start value using the reset() method.


9. Multiple Iterators in Parallel

This example shows how to iterate over multiple collections in parallel, yielding elements from each one.

Output:

This iterator iterates through multiple iterables and returns a list of corresponding elements from each iterable.


10. Custom Range with Step

You can add a custom step value to your iterator.

Output:

This iterator generates numbers from start to end with a custom step value.


These examples demonstrate how you can implement the iterator protocol using `iter

()andnext()` methods in Python. You can adapt the iterator behavior to your specific needs, whether you want to create infinite sequences, iterate over files, or create custom stepping patterns.

Last updated