Python next() function

Published February 16, 2022

The 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])
item = next(my_iterator)
print(item)
item = next(my_iterator)
print(item)
item = next(my_iterator)
print(item)


Output

78
76
72

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

255 Views