89DEVs

Python next() function

overview of next()

The next() function returns the next item from an iterator object, which can be created using the iter() function. It can then be used to iterate through one element at a time.

use of next()

The next() function can be used together with the iter() function to iterate through all elements of an iterable. # use of next() with default value letters = ['a', 'b', 'c', 'd', 'e'] lettersIter = iter(letters) print(next(lettersIter, '-')) print(next(lettersIter, '-')) print(next(lettersIter, '-')) print(next(lettersIter, '-')) print(next(lettersIter, '-')) print(next(lettersIter, '-')) The next() function returns the next letter in the iterator object five times. For the last call no item is left in the iter object, therefore the default value '-' is returned. A StopIteration Error exception is not raised in this case, because we have defined a default value for the next() calls. a b c d e -

syntax of next()

The syntax of next() is: next(iterator[, default])

arguments of next()

The next() function accepts two arguments: The first argument is the iterator object and is required. The second argument is the default value and is optional. The default value defines what is returned, if no next item is left in the iterator.

return value of next()

The next() function returns the next item from the iterator object. If no item is left, by default an StopIteration exception is raised. This can be modified by using the second parameter to define a default value.

                
        

Summary


Click to jump to section