Google News
logo
Python Program to Stop iteration
In the following example of how to stop iteration using the `StopIteration` exception in Python :
Program :
# Define a custom iterator
class MyIterator:
    def __init__(self, start, end):
        self.current = start
        self.end = end

    def __iter__(self):
        return self

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

# Use the iterator to print numbers from 0 to 4
my_iterator = MyIterator(0, 5)
for num in my_iterator:
    print(num)
Output :
0
1
2
3
4
In this example, we define a custom iterator `MyIterator` that generates numbers from a given start value to an end value.

The `__next__()` method is responsible for generating the next value in the iterator. When there are no more values to generate, we raise the `StopIteration` exception. This tells the caller that the iterator has reached the end of its sequence.

We then use this custom iterator in a `for` loop to print numbers from 0 to 4. When the iterator reaches the end of its sequence, the `for` loop stops iterating.