Python next() is an inbuilt function that returns the next item from an iterator. The next() function is used to fetch the next item from the collection. It takes two arguments an iterator and a default value and returns an element. This method calls on iterator and throws an error if no item is present. To avoid the error, we can set a default value.
Python next() method returns the next element from the list, if not present prints the default value. If the default value is not present, raise the StopIteration error. You can add a default return value, to return if the iterable has reached its end.
Syntax:
next (iterator[, default])
Parameters
Return
Example 1:
Here, we are getting items using next() function. It does not require any loop or indices.
# 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
Example 2
This function throws an error when reaches the end of the collection. See the example 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, in
item = next(number)
StopIteration
256
32
82
#python #python next