English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Utilisation et exemples de next() en Python

Python built-in functions

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

La syntaxe de next() est :

next(iterator, valeur par défaut)

paramètre next()

  • iterator- next() fromin the iteratorRetrieve the next item

  • default (optional)-If the iterator is exhausted, it will return this value (no next item)

next() return value

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

  • If the iterator is exhausted, it will return the value passed as the parameter of the default.

  • If omittedDefault(default) parameter, andIterators(iterator) is exhausted, it will raise a StopIteration exception.

Example1: Get the next item

random = [5, 9, 'cat']
# Convert list to iterator
random_iterator = iter(random)
print(random_iterator)
# Output: 5
print(next(random_iterator))
# Output: 9
print(next(random_iterator))
# Output: 'cat'
print(next(random_iterator))
# This will cause an error
# iterator exhausted
print(next(random_iterator))

Output result

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

list is  iterableYou can use the iter() function in Python to get its  Iterators.

Learn more about

We got an error from the last statement of the above program because we tried to get the next item without the next item available (the iterator has been exhausted).

In this case, you can provideDefaultAs the second parameter.

Example2:Pass the default value to next()

random = [5, 9]
# Convert list to iterator
random_iterator = iter(random)
# Output: 5
print(next(random_iterator, '-1'))
# Output: 9
print(next(random_iterator, '-1'))
# random_iterator is exhausted
# Output: '-1'
print(next(random_iterator, '-1'))
print(next(random_iterator, '-1'))
print(next(random_iterator, '-1'))

Output result

5
9
-1
-1
-1

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

Python built-in functions