Python next()

The next() function returns the next item from the iterator.

Example


next() Syntax

The syntax of next() is:

next(iterator, default)

next() Parameters

  • iterator - next() retrieves next item from the iterator
  • default (optional) - this value is returned if the iterator is exhausted (there is no next item)

next() Return Value

  • The next() function returns the next item from the iterator.
  • If the iterator is exhausted, it returns the default value passed as an argument.
  • If the default parameter is omitted and the iterator is exhausted, it raises the StopIteration exception.

Example 1: Get the next item

Output

<list_iterator object at 0x7feb49032b00>
5
9
cat
Traceback (most recent call last):
  File "python", line 18, in <module>
StopIteration

A list is an iterable and you can get its iterator from it by using the iter() function in Python.

Learn more about

We got an error from the last statement in the above program because we tried to get the next item when no next item was available (iterator is exhausted).

In such cases, you can give a default value as the second parameter.


Example 2: Passing default value to next()

Output

5
9
-1
-1
-1

Note: Internally, next() calls the __next__() method.