English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The next() function returns the next item from the iterator.
La syntaxe de next() est :
next(iterator, valeur par défaut)
iterator- next() fromin the iteratorRetrieve the next item
default (optional)-If the iterator is exhausted, it will return this value (no next item)
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.
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.
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.