
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Catch StopIteration Exception in Python
StopIteration Exception in Python
The StopIteration exception in Python is raised to indicate that there are no more items left in an iterator to retrieve. It occurs when a call to the next() or, __next__() reaches the end of an iterable.
In this article, you will learn how and when StopIteration is raised, and how to catch and handle it using try-except blocks.
When Does StopIteration Occur?
When can retrieve the contents of an Iterator object, using the Python built-in function next() or the __next__() method (of the iterator object). The next() function internally calls the _next__() method. These methods return the next available element in the current iterator object.
While retrieving the elements, if we reach the end of the iterator object, i.e., there are no more elements in it, a StopIteration exception is raised. The StopIteration exception occurs in the following cases -
- When manually calling the next() function or __next__() method on an iterator that has no more elements.
- In custom iterator classes, the end of the data is reached.
Example: Catching StopIteration with next()
In the following example, we use the next() function on a list iterator and catch StopIteration when the elements are exhausted -
my_list = [10, 20, 30] iterator = iter(my_list) try: print(next(iterator)) print(next(iterator)) print(next(iterator)) print(next(iterator)) # This will raise StopIteration except StopIteration: print("No more items to iterate.")
Following is the output obtained -
10 20 30 No more items to iterate.
Example: Catching StopIteration in a While Loop
In this example, we manually loop through an iterator using a while statement and break the loop when a StopIteration exception is raised -
my_tuple = ('a', 'b', 'c') it = iter(my_tuple) while True: try: item = next(it) print("Item:", item) except StopIteration: print("End of iteration.") break
We get the output as shown below -
Item: a Item: b Item: c End of iteration.
Example: Custom Iterator Raising StopIteration
When you define a custom iterator, you need to raise StopIteration explicitly to signal that there are no more items to return -
class CountUpToThree: def __init__(self): self.num = 1 def __iter__(self): return self def __next__(self): if self.num > 3: raise StopIteration value = self.num self.num += 1 return value it = CountUpToThree() for i in it: print(i)
The output obtained is as shown below -
1 2 3