The next function in Python is utilized to retrieve the subsequent item from a collection. It accepts two parameters: an iterator and an optional default value, and it returns the next element from the iterator.
This approach utilizes an iterator and raises an exception if there are no items available. To prevent this exception from occurring, we can specify a default value.
Python next Function Syntax
The syntax of the function is given below.
next (iterator[, default])
Parameters
- iterator : It is an iterator object.
- default : This value returns if the element is not present.
Return
It returns an item from the collection.
Different Examples for Python next Function
Let’s explore a few instances of the next function to grasp its capabilities.
Python next Function Example 1
In this instance, we are retrieving elements through the use of the next function. This approach does not necessitate any loops or index references.
# Python next() function example
number = iter([256, 32, 82]) # Creating iterator
# Calling function
item = next(number)
# Displaying result
print(item)
# second item
item = next(number)
print(item)
# third item
item = next(number)
print(item)
Output:
256
32
82
Python next Function Example 2
This function generates an error upon reaching the conclusion of the collection. Refer to the illustration provided below.
# Python next() function example
number = iter([256, 32, 82]) # Creating iterator
# Calling function
item = next(number)
# Displaying result
print(item)
# second item
item = next(number)
print(item)
# third item
item = next(number)
print(item)
# fourth item
item = next(number) # error, no item is present
print(item)
Output:
Traceback (most recent call last):
File "source_file.py", line 14, initem = next(number)
StopIteration
256
32
82
Python next Function Example 3
# Python next() function example
number = iter([256, "Example", 82,]) # Creating iterator
# Calling function
item = next(number)
# Displaying result
print(item)
# second item
item = next(number)
print(item)
# third item
item = next(number)
print(item)
# fourth item
item = next(number, "No item is present") # error, no item is present
print(item)
Output:
256
Example
82
No item is present
Python next Function Example 4
In this context, we are assigning a default value. Consequently, rather than generating an error, it instead provides the default value.
# Python next() function example
number = iter([256, "Example", 82,]) # Creating iterator
# Calling function
item = next(number)
# Displaying result
print(item)
# second item
item = next(number)
print(item)
# third item
item = next(number)
print(item)
# fourth item
item = next(number, "No item is left") # no error due to default value
print(item)
Output:
256
Example
82
No item is left