Menu Close

Python next() Function

python next tutorial

In this guide, we are going to see everything about the Python next() function and how to use the next() function 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 item object.

Python next function Introduction

Python’s 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 the 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 the next() function in Python is the next item of the iterable.

Python next example

Here we will see some examples to understand the next() function in Python.

Example: Using next() function without for loop


#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: Using next() function with for loop for loop


#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: Using the next() function with a default value

Here we will use the next() function with a 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 get 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

Thanks for your valuable time …. ❤️❤️

Python open Function
Python max() Function

Related Posts