Skip to Content
Clean Code in Python
book

Clean Code in Python

by Mariano Anaya
August 2018
Intermediate to advanced
332 pages
9h 12m
English
Packt Publishing
Content preview from Clean Code in Python

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, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Clean Code in Python - Second Edition

Clean Code in Python - Second Edition

Mariano Anaya
Python for Programmers

Python for Programmers

Paul Deitel, Harvey Deitel

Publisher Resources

ISBN: 9781788835831Supplemental Content