Introduction to Python StopIteration
The following article provides an outline for Python StopIteration. As we are well aware of the topic ‘iterator’ and ‘iterable’ in Python. The basic idea of what the ‘iterator’ is? Iterator is basically an object that holds a value (generally a countable number) which is iterated upon. Iterator in Python uses the __next__() method in order to traverse to the next value. In order to tell that there are no more values that need to be traversed by the __next__() method, a StopIteration statement is used. Programmers usually write a terminating condition inside __next__() method in order to stop it after the specified condition is reached.
Syntax of Python StopIteration
When the specified number of iterations are done, StopIteration is raised by the next method in case of iterators and generators (works similar to iterators except it generates a sequence of values at a time instead of a single value). If we go in deep understanding of Python, the situation of raising ‘StopIteration’ is not considered as an error. It is considered an Exception and can be handled easily by catching that exception similar to other exceptions in Python.
General syntax of using StopIteration in if and else of next() method is as follows:
… #set of statements
if …. #condition till the loop needs to be executed
…. #set of statements that needs to be performed till the traversing needs to be done
raise StopIteration #it will get raised when all the values of iterator are traversed
How StopIteration works in Python?
StopIteration stops the iterations after the maximum limit is reached or it discontinues moving the loop forever.
Key points that needs to be keep in mind to know the working of StopIteration in Python are as follows:
- It is raised by the method next() or __next__() which is a built-in method in python 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 and catching the exception using the ‘except’ keyword and printing it on screen using the ‘print’ keyword.
- Value returned by raising the StopIteration is used as a parameter of the Exception Constructor in order to perform the desired actions.
- next() 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:
Stop the printing of numbers after 20 or printing numbers incrementing by 2 till 20 in case of Iterators.
self.z = 2
if self.z<= 20: #performing the action like printing the value on console till the value reaches 20
y = self.z
self.z += 2
raise StopIteration #raising the StopIteration exception once the value gets increased from 20
obj = printNum()
value_passed = iter(obj)
for u in value_passed:
- In the above example, in order to iterate through the values, two methods, i.e. iter() and next() are used. If we see, in the next() method if and else statements are used in order to check when the iteration and hence their respective actions (which is printing of values in this case) should get terminated.
- If the iterable value is less than or equals to 20, it continues to print those values at the increment of 2. Once the value reaches greater than 20, the next() method raises an StopIteration exception.
Finding the cubes of number and stop executing once the value becomes equal to the value passed using StopIteration in case of generators.
defvalues(): #list of integer values with no limits
x = 1 #initializing the value of integer to 1
for x in values():
yield x * x *x #finding the cubes of value ‘x’
sequence = iter(sequence)
output = [ ]#creating an output blank array
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
print(func(5, findingcubes())) #passing the value in the method ‘func’
- In the above example, we are finding the cubes of number from 1 till the number passed in the function. We are generating multiple values at a time using the generators in Python and in order to stop the execution once the value reaches the one passed in the function, StopIteration exception is raised.
- Different methods are created serving their respective purpose like generating the values, finding the cubes and printing the value by storing them in the output array. Basic python functions are used in the program like range, append, etc which should be clear in the initial stages of learning to the programmer.
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 the two methods, i.e. iter() and next().
- The next() method raises an 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 again and again.
- Otherwise if not able to avoid StopIteration exception in Python, we can simply raise the exception in next() method and catch the exception like a normal exception in Python using the except keyword.
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. But proper understanding of its scenarios in which it could be raised and techniques to avoid it can help them to program better.
This is a guide to Python StopIteration. Here we discuss how StopIteration works in python and how to avoid StopIteration exception with programming examples. You may also have a look at the following articles to learn more –