Introduction to Python StopIteration
The following article outlines Python StopIteration as we know the topic ‘iterator’ and ‘iterable’ in Python. The basic idea of what the ‘iterator’ is? An iterator is an object that holds a value (generally a countable number) that is iterated upon. Iterator in Python uses the __next__() method to traverse to the next value. To tell that no more deals need to be traversed by the __next__() process, a StopIteration statement is used. Programmers usually write a terminating condition inside the __next__() method to stop it after reaching the specified state.
Syntax of Python StopIteration
When the method used for iterators and generators completes a specified number of iterations, it raises the StopIteration exception. It’s important to note that Python treats raising StopIteration as an exception rather than a mistake. Like how Python handles other exceptions, this exception can be handled by catching it. This active handling of the StopIteration exception allows for proper control and management of the iteration process, ensuring that the code can gracefully handle the termination of the iteration when required.
The general syntax of using StopIteration in if and else of next() method is as follows:
class classname:
def __iter__(self):
…
… #set of statements
return self;
def __next__(self):
if …. #condition till the loop needs to be executed
…. #set of statements that needs to be performed till the traversing needs to be done
return …
else
raise StopIteration #it will get raised when all the values of iterator are traversed
How StopIteration works in Python?
- It is raised by the method next() or __next__(), a built-in Python method to stop the iterations or to show that no more items are left to be iterated upon.
- We can catch the StopIteration exception by writing the code inside the try block, catching the exception using the ‘except’ keyword, and printing it on screen using the ‘print’ keyword.
- The following () method in both generators and iterators raises it when no more elements are present in the loop or any iterable object.
Examples of Python StopIteration
Given below are the examples mentioned:
Example #1
Stop the printing of numbers after 20 or printing numbers incrementing by 2 till 20 in the case of Iterators.
Code:
class printNum:
def __iter__(self):
self.z = 2
return self
def __next__(self):
if self.z <= 20: #performing the action like printing the value on console till the value reaches 20
y = self.z
self.z += 2
return y
else:
raise StopIteration #raising the StopIteration exception once the value gets increased from 20
obj = printNum()
value_passed = iter(obj)
for u in value_passed:
print(u)
Output:
Explanation:
- In the above example, we use two methods, namely iter() and next(), to iterate through the values. The next() method utilizes if and else statements to check for the termination condition of the iteration actively.
- If the iterable value is less than or equal to 20, it continues to print those values at the increment of 2. Once the value exceeds 20, the next() method raises a StopIteration exception.
Example #2
Finding the cubes of number and stop executing once the value becomes equal to the value passed using StopIteration in the case of generators.
Code:
def values(): #list of integer values with no limits
x = 1 #initializing the value of integer to 1
while True:
yield x
x+= 1
def findingcubes():
for x in values():
yield x * x *x #finding the cubes of value ‘x’
def func(y, sequence):
sequence = iter(sequence)
output = [ ] #creating an output blank array
try:
for x in range(y): #using the range function of python to use for loop
output.append(next(sequence)) #appending the output in the array
except StopIteration: #catching the exception
pass
return output
print(func(5, findingcubes())) #passing the value in the method ‘func’
Output:
Explanation:
- In the above example, we find the cubes of numbers from 1 to the number passed in the function. We generate multiple values at a time using generators in Python, and to stop the execution once the value reaches the one passed in the function, we raise a StopIteration exception.
- We create different methods serving their respective purposes, such as generating the values, finding the cubes, and printing the values by storing them in the output array. The program uses basic Python functions like range and append, which should be clear to the programmer in the initial stages of learning.
How to Avoid StopIteration Exception in Python?
- As seen above StopIteration is not an error in Python but an exception and is used to run the next() method for the specified number of iterations. Iterator in Python uses two methods, i.e. iter() and next().
- The next() method raises a StopIteration exception when the next() method is called manually.
- The best way to avoid this exception in Python is to use normal looping or use it as a normal iterator instead of writing the next() method repeatedly.
- Otherwise, if not able to avoid StopIteration exception in Python, we can simply raise the exception in the next() method and catch the exception like a normal exception in Python using the except keyword.
Conclusion
As discussed above in the article, it must be clear to you what is the StopIteration exception and in which condition it is raised in Python. StopIteration exception could be an issue to deal with for the new programmers as it can be raised in many situations.
Recommended Articles
This is a guide to Python StopIteration. Here we discuss how StopIteration works in Python and how to avoid StopIteration exceptions with programming examples. You may also have a look at the following articles to learn more –