In this guide, we are going to show you what is python next() function and how to use them to find the next item of an iterable.
To understand this example, you should have basic knowledge of the Python iter() function to get the iter object.
Table of Contents
Python next function
Python next function is a built-in function that is used to find the next item of an iterable. You can add a default value, to return if the iterable reached the end.
Syntax
The syntax of next function in Python is:-
next(iterable, default)
Parameters
next function in Python accepts two parameters.
- iterable:- Required, An iterable object
- default:- Optional. A default value if the iterable reached the end.
Return Value
The return value of next function in Python is next item of iterable.
Python next example
Here we will see some example to understand next function in Python.
Example 1:
#List iterable
my_iterable = ['Python', 'C#', 'Java', 'PHP', 'Ruby']
#Create iterator object.
iter_object = iter(my_iterable)
print(next(iter_object))
print(next(iter_object))
print(next(iter_object))
print(next(iter_object))
print(next(iter_object))
Output
Python
C#
Java
PHP
Ruby
Example 2:
#List iterable
my_iterable = ['Python', 'C#', 'Java', 'PHP', 'Ruby']
#Create iterator object.
iter_object = iter(my_iterable)
for i in range(len(my_iterable)):
print(next(iter_object))
Output
Python
C#
Java
PHP
Ruby
Example 3:
Here we will use next function with default value.
#List iterable
my_iterable = ['Python', 'C#', 'Java', 'PHP', 'Ruby']
#Create iterator object.
iter_object = iter(my_iterable)
for i in range(len(my_iterable) + 1):
print(next(iter_object, 'HTML'))
output
Python
C#
Java
PHP
Ruby
HTML
Conclusion
In this article, you have learned all about the Python next() function to getting the next item of iterable.
To understand the next function, you should have knowledge of the Python iter() function.
If you like this article, please share and keep visiting for further python built-in functions tutorials.
Python built-in functions
For more information:- Click Here