The next() function

The next() built-in function will advance the iterable to its next element and return it:

>>> word = iter("hello")>>> next(word)'h'>>> next(word)'e'  # ...

If the iterator does not have more elements to produce, the StopIteration exception is raised:

>>> ...>>> next(word)'o'>>> next(word)Traceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration>>>

This exception signals that the iteration is over and that there are no more elements to consume.

If we wish to handle this case, besides catching the StopIteration exception, we could provide this function with a default value in its second parameter. Should this be provided, it will be the return value in lieu of throwing StopIteration:

>>> next(word, ...

Get Clean Code in Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.