next

Full name
next
Library
Built-in
Syntax

next(iterator [, default])

Description

The next function returns the next element of the iterator included as the first argument by invoking its __next__ method.

In the case that the iterator is empty, an exception of type StopIteration will be generated unless a second argument ("default") has been included, in which case it will be returned as a result of the function.

Parameters
  • iterator: Iterator from which to extract the next element.
  • default: Value to return if there are no elements in the iterator.
Result

The next function returns an element of the specified iterable, whatever type it may be.

Examples

If we start from the following iterator created from a list:

a = iter ([2, 4, 6, 8])

...we can extract its first value by executing the next function and passing the iterator as an argument:

next(a)

2

Each execution of the next function will return the following element:

next(a)

4

next(a)

6

next(a)

8

...until the iterator includes no more elements, in which case an exception is returned:

next(a)

-------------------------------------------------- -------------------------
StopIteration Traceback (most recent call last)
in
----> 1 next (a)

StopIteration:

If the second argument, default, is included, it will be the value returned when the iterable does not include any elements. For example, we start from the same iterator as in the previous example:

a = iter([2, 4, 6, 8])

...and we execute a while loop reading the next element until it is None, value included as second argument in the next function:

result = ""
while result != None:
    result = next(a, None)
    print(result)

2
4
6
8
None

Submitted by admin on Thu, 01/14/2021 - 18:14