An iterator is an object that implements the iteration protocol, which consists of two methods: __iter__()
and __next__()
. The __iter__()
method is called when an iterator object is initialized.The __next__()
method is called to retrieve the next item from the iterator.
The StopIteration
exception is raised when the __next__()
method of an iterator object is called but there are no items to iterate over. This exception is used to signal the end of iteration.
The builtin next() function is used to retrieve the next item from an iterator object. It actually calls the __next__()
method of the iterator object.
Handling StopIteration exceptions
The most obvious way to handle a StopIteration exception is to use a for
loop. The for
loop allows you to iterate over the sequence until a StopIteration exception is raised. The loop handles the exception automatically for you.
You can also use the try-except
blocks to handle the exception explicitly.
When using while loop: