Python next()

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

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 (no items left)

Return Value from next()

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

If the iterator is exhausted, it returns default value (if provided).

If the default parameter is omitted and iterator is exhausted, it raises StopIteration.


Example 1: How next() works?

random = [5, 9, 'cat']

# converting list to iterator
randomIterator = iter(random)
print(randomIterator)

# Output: 5
print(next(randomIterator))

# Output: 9
print(next(randomIterator))

# Output: 'cat'
print(next(randomIterator))

# This will raise Error
# iterator is exhausted
print(next(randomIterator))

When you run the program, the output will be:

<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 iterator from it by using iter() function in Python.

Learn more about

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

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


Example 2: Iterator With Default Value

random = [5, 9]

# converting list to iterator
randomIterator = iter(random)

# Output: 5
print(next(randomIterator, '-1'))

# Output: 9
print(next(randomIterator, '-1'))

# randomIterator is exhausted
# Output: '-1'
print(next(randomIterator, '-1'))
print(next(randomIterator, '-1'))
print(next(randomIterator, '-1'))

When you run the program, the output will be:

5
9
-1
-1
-1