[Solved]: StopIteration in Python


In Python, StopIteration 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 StopIteration

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.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s