[Solved]: StopIteration in Python

Python StopIteration Error is an exception which occurred by built-in next() and __next__() method in iterator to signal that iteration is done for all items and no more to left to iterate.

Example of Python StopIteration Error

In this example string value “FacingIssuesOnIT” is Iterating to print character. In this case while loop will run indefinitely and call next() method on iterable value to print value.

iterable_value = 'FacingIssuesOnIT'
iterable_obj = iter(iterable_value)
 
while True:
    try: 
        # Iterate by calling next
        item = next(iterable_obj)
        print(item)
    except StopIteration as err:
        print('Stop Iteration occured')
        break

Output

F
a
c
i
n
g
I
s
s
u
e
s
O
n
I
T
Stop Iteration occurred

In this program after completing the iteration next() element print of iterable_value when it goes to next element print it will throw StopIteration exception because there is no more element in iterable_value.

Solution

Whenever you apply the next() method of iterable object always check the length of iterable object then run the loop to get element by next() method otherwise through Python StopIteration Error.

Related Posts

Your Feedback Motivate Us

If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

Happy Learning !!!