Menu
Coddy logo textTech

StopIteration Exception

Lesson 3 of 13 in Coddy's Python Iterators course.

The StopIteration exception is a crucial component in Python's iterator protocol. It signals the end of an iteration sequence and plays a vital role in controlling iterator behavior. Let's explore this exception and its importance.

What is StopIteration?

StopIteration is a built-in exception in Python that is raised when an iterator is exhausted, meaning there are no more items to be returned.

When is StopIteration Raised?

The StopIteration exception is automatically raised by Python in two main scenarios:

  1. When the next() function is called on an iterator that has no more items.
  2. When a custom iterator's __next__() method is implemented to raise StopIteration at the end of the iteration.

Example of StopIteration

Let's see how StopIteration works with a simple iterator:

my_list = [1, 2, 3]
my_iterator = iter(my_list)

print(next(my_iterator))  # Output: 1
print(next(my_iterator))  # Output: 2
print(next(my_iterator))  # Output: 3
print(next(my_iterator))  # Raises StopIteration

In this example, after we've iterated through all elements of my_list, the next call to next() raises a StopIteration exception.

Importance in Iterator Behavior

The StopIteration exception is crucial for several reasons:

  1. Signaling the End: It provides a clear signal that the iteration has reached its end.
  2. For Loop Termination: Python's for loops rely on StopIteration to know when to terminate.
  3. Custom Iterator Control: When creating custom iterators, raising StopIteration allows you to define when the iteration should end.

Handling StopIteration

While for loops handle StopIteration automatically, when using next() directly, you might want to handle this exception explicitly:

my_iterator = iter([1, 2, 3])

try:
    while True:
        item = next(my_iterator)
        print(item)
except StopIteration:
    print("Iteration finished")

This code will print the numbers 1, 2, and 3, followed by "Iteration finished" when the StopIteration exception is caught.

Understanding the StopIteration exception is essential for working with iterators in Python, as it provides the mechanism for controlling and ending iterations in a standardized way.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create a custom iterator that generates a sequence of prime numbers up to a given limit. The iterator should use the StopIteration exception to signal the end of the sequence when it reaches or exceeds the limit.

You are provided with the following:

  • An integer limit as input

Your iterator should:

  • Generate prime numbers starting from 2
  • Raise a StopIteration exception when the next prime number would exceed the given limit

Implement the iterator as a class with __iter__() and __next__() methods. Use the __next__() method to generate the next prime number and handle the StopIteration exception.

Print each generated prime number on a new line.

The input will be provided as a string representing an integer.

Try it yourself

# Read input
limit = int(input())

class PrimeIterator:
    def __init__(self, limit):
        self.limit = limit
        self.current = 2

    def __iter__(self):
        return self

    def __next__(self):
        # TODO: Implement the logic to generate the next prime number
        # If the next prime number exceeds the limit, raise StopIteration
        # Return the next prime number if it's within the limit
        pass

# Create an instance of PrimeIterator
prime_iter = PrimeIterator(limit)

# Iterate through the prime numbers and print each one
try:
    for prime in prime_iter:
        print(prime)
except StopIteration:
    pass  # End of iteration

All lessons in Python Iterators