Python next()


Python next() is a built-in function that returns the next item from an iterator.

python next() function

Python next() Syntax

next(iterator[, default])

next() method takes two arguments.

  • iterator (required) – the iterator from which next item is to returned
  • default (optional) – value to be returned of iterator is exhausted else StopIteration error is raised

The next() method keeps on returning the next time in the iterator till there are no items left in the iterator. When the end of an iterator is reached, program searches for the default value. If a default value is not given for such cases, then it will raise StopIteration error.

next() method internally uses the built-in __next__() module to fetch the next item from the iterator.

Recommended readingPython Iterators ( __iter__ And __next__ ) | Explanation And Example

Python next() Example

>>> x = ['Hey','there','Python','programmers']
>>> obj = iter(x) #using iter function for x
>>> next(obj) #Iteration 1 using next function
'Hey'
>>> next(obj) #Iteration 2
'there'
>>> next(obj) #Iteration 3
'Python'
>>> next(obj) #Iteration 4
'programmers'
>>> next(obj) #Iteration 5
Traceback (most recent call last):
 ...
StopIteration

Note: obj is the iterator returned by the function __iter__().

Notice in 5th iteration the __next__() function raises an exception called StopIteration because there is no any item left to iterate through and we have not provided any default value.

Now let’s try the same program by providing a default value.

Python next() method with a default value

>>> x = ['Hey','there','Python','programmers']
>>> obj = iter(x) #using iter function for x
>>> next(obj) #Iteration 1 using next function
'Hey'
>>> next(obj, 1) #Iteration 2
'there'
>>> next(obj, 1) #Iteration 3
'Python'
>>> next(obj, 1) #Iteration 4
'programmers'
>>> next(obj, 1) #Iteration 5
1
>>> next(obj, 1) #Iteration 6
1

As you can see in above example instead of throwing a StopIteration error, next() methods returned the default value 1 when the iterator was exhausted after 5 iterations.