next() - Next item in Iterator - Python Examples


Python - next()

Python next() built-in function returns the next item from the iterator object by calling iterator's __next__() method.

In this tutorial, we will learn the syntax and usage of next() built-in function with examples.

Syntax

The syntax of next() function is

next(iterator)
next(iterator, default)

where

ParameterMandatory/
Optional
Description
iteratorMandatoryA Python iterator object.
defaultOptionalDefault value that next() has to return if there is no next item in the iterator.

Examples

1. Get next objects from iterator

In the following program, we take a list in myList, get its iterator using the iter() built-in function, and print the next items in the iterator using next().

Python Program

myList = ['apple', 'banana', 'cherry']
myIterator = iter(myList)
print(next(myIterator))
print(next(myIterator))
print(next(myIterator))

Output

apple
banana
cherry

2. Get next objects from iterator with Default value

In the following program, we make a call to the next() function with iterator and default value passed as arguments.

When there are no next() elements to return from the iterator object, next() returns the default value.

Python Program

myList = ['apple', 'banana', 'cherry']
myIterator = iter(myList)
print(next(myIterator, 'NA'))
print(next(myIterator, 'NA'))
print(next(myIterator, 'NA'))
print(next(myIterator, 'NA'))
print(next(myIterator, 'NA'))

Output

apple
banana
cherry
NA
NA

We have exhausted the items in the iterator in the first three calls. For the last two next() function calls, there are no items in the iterator. Therefore, next() has returned the default value with is the string 'NA'.

Related Tutorials

Summary

In this Built-in Functions tutorial, we learned the syntax of the next() built-in function, and how to use this function to get the next value from an iterator object, with examples.