StopIteration Exception in Python

By Lenin Mishra

This is the part of the 9th day in the Python 30 series. Check out the series here.

To understand StopIteration Exception, you need to understand how iterators work in Python.

  1. Iterator is an object that holds values which can be iterated upon.
  2. It uses the __next__() method to move to the next value in the iterator.
  3. When the __next__() method tries to move to the next value, but there are no new values, a StopIteration Exception is raised.
Example 1

Code

y = [1, 2, 3]
x = iter(y)
print(x.__next__())
print(x.__next__())
print(x.__next__())
print(x.__next__())

Output

1
2
3
Traceback (most recent call last):
  File "some_file_location", line 6, in <module>
    print(x.__next__())
StopIteration

You can catch such errors using the StopIteration Exception class.

Example 2

Code

y = [1, 2, 3]
x = iter(y)
try:
    print(x.__next__())
    print(x.__next__())
    print(x.__next__())
    print(x.__next__())
except StopIteration as e:
    print("StopIteration error handled successfully")

Output

1
2
3
StopIteration error handled successfully

Check out other Python Built-in Exception classes in Python.

  1. Try, Except, Else and Finally in Python
  2. ZeroDivisionError Exception in Python
  3. OverflowError Exception in Python
  4. ArithmeticError Exception in Python
  5. KeyError Exception in Python
  6. IndexError Exception in Python
  7. LookupError Exception in Python
  8. TypeError Exception in Python
  9. NameError Exception in Python
  10. FileNotFoundError Exception in Python
  11. Catch Multiple Exceptions in Python