This guide deals with the Python next function and it’s uses, complete with several examples.

The Python next function is used with iterables. It has the ability to retrieve the ‘next’ item in the iterable’s sequence. If it has reached the end of the iterable, it has the ability to output a default value.

Syntax

The next function takes up-to parameters, where the iterable is the compulsory one, and default is the optional one.

next(iterable, default)
  • The iterable must be an iterable object, such as the objects produced by the iter function. If you don’t know about the iter function, read up on it first.
  • The value stored in default is the value that gets printed if the end of the sequence has been reached, and a next function was called. You should always include a default value to avoid any exceptions and your program crashing.

If the default value was not included, and the end of sequence was exceeded, a StopIteration exception will be thrown.


Example Set 1:

Here we are, first creating an iterable object, and then calling the next function on it, printing it out each time. At the 4th next call, an exception is thrown. Let’s try it again with the default value set.

X = iter(["Apple", "Banana", "Cucumber"])
print(next(X))
print(next(X))
print(next(X))
print(next(X))
Apple
Banana
Cucumber
Traceback (most recent call last):
  File "C:\Users\Shado\Desktop\DIEEE.py", line 7, in <module>
    print(next(X))
StopIteration

Example Set 2:

Here, we have the default value as “End of Sequence”. This will now print in place of the iterable object if the iterable becomes exhausted.

X = iter(["Apple", "Banana", "Cucumber"])
print(next(X, "End of Sequence"))
print(next(X, "End of Sequence"))
print(next(X, "End of Sequence"))
print(next(X, "End of Sequence"))
Apple
Banana
Cucumber
End of Sequence

This marks the end of the Python next Function Article. Any suggestions or contributions for CodersLegacy are more than welcome. Any questions can be asked in the comments section below.

Head back to the main Built-in Function Article using this link.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments