Python next() function
Published February 16, 2022The next() method in Python returns the next element from a given collection based on a list of items. To return the next element, this method takes two arguments: a default value and an iterator. The method will throw an error if no item exists since the method uses the iterator. To prevent errors, we must set the default value.
Syntax
The following is the syntax of the next() function
next(iterator, default) |
where:
iterator: this is the iterator object created using the iter function
default: As a default value, this is what will be returned when an iterator becomes exhausted
This method returns the next value from the iterator.
Example
In the example below, we are going to use the next() function to obtain the next value of the iterator.
my_iterator = iter([78, 76, 72]) |
Output
78 |
Article Contributed By :
|
|
|
|
255 Views |