StopIteration
StopIteration
is a built-in exception that signals the end of an iteration when an iterator has no more items to return.
Python uses it internally to manage iteration processes, particularly in for
loops and comprehensions.
StopIteration
Occurs When
- A
for
loop finishes iterating over an iterator - The
next()
function is called on an iterator that has no more items
If StopIteration
occurs as a normal part of executing a loop, then you won’t see the exception. This is because Python handles it internally.
StopIteration
Can Be Used When
You can use StopIteration
when creating custom iterators. You’ll raise this exception in the .__next__()
method to signal the end of the iteration.
StopIteration
Examples
An example of when the exception appears:
>>> numbers_iterator = iter([1, 2, 3])
>>> next(numbers_iterator)
1
>>> next(numbers_iterator)
2
>>> next(numbers_iterator)
3
>>> next(numbers_iterator)
Traceback (most recent call last):
...
StopIteration
An example of how to handle the exception:
>>> numbers_iterator = iter([1, 2, 3])
>>> while True:
... try:
... number = next(numbers_iterator)
... print(number)
... except StopIteration:
... break
...
1
2
3
An example of when to raise the exception:
custom_iterator.py
class CustomIterator:
def __init__(self, data):
self.data = data
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.data):
raise StopIteration
result = self.data[self.index]
self.index += 1
return result
# Usage
iterator = CustomIterator([1, 2, 3])
for item in iterator:
print(item) # Output: 1 2 3
Related Resources
Tutorial
Iterators and Iterables in Python: Run Efficient Iterations
In this tutorial, you'll learn what iterators and iterables are in Python. You'll learn how they differ and when to use them in your code. You'll also learn how to create your own iterators and iterables to make data processing more efficient.
For additional information on related topics, take a look at the following resources:
- Python's Built-in Exceptions: A Walkthrough With Examples (Tutorial)
- Python's raise: Effectively Raising Exceptions in Your Code (Tutorial)
- Efficient Iterations With Python Iterators and Iterables (Course)
- Iterators and Iterables in Python: Run Efficient Iterations (Quiz)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Using raise for Effective Exceptions (Course)
- Python's raise: Effectively Raising Exceptions in Your Code (Quiz)