Python built-in Method - next()

The next() function is a built-in Python method that returns the next item from an iterator. An iterator is an object that produces a sequence of values, one at a time, when you call the next() function on it.

The syntax for the next() function is as follows:

next(iterator[, default])
‮w:ecruoS‬ww.theitroad.com
  • iterator: The iterator object from which the next value is to be obtained.
  • default: An optional value that will be returned if the iterator is exhausted.

Here's an example usage of the next() function:

>>> lst = [1, 2, 3, 4, 5]
>>> it = iter(lst)  # create an iterator from the list
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3

In the above example, we create an iterator object it from the list lst using the iter() function. We then call the next() function on the iterator object it three times, which returns the next element in the list each time.

If there are no more elements in the iterator, and the default parameter is not provided, then the next() function raises a StopIteration exception. However, if the default parameter is provided, then that value is returned instead of raising an exception.

>>> it = iter([1, 2, 3])
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it, 'default')
'default'

In the above example, we create an iterator object it from the list [1, 2, 3] using the iter() function. We then call the next() function four times. The first three calls to next() return the elements of the list. The fourth call to next() returns the default value 'default' because there are no more elements in the iterator.