Tutorial Study Image

Python next()

The built-in function next() is used to return the next element from an iterator. Typically this function used in a loop. When it reaches the end of the iterator it will throw an error to avoid this situation we can specify the default value.


next(iterator, default) #where iterable can be list, tuple etc
 

next() Parameters:

Takes two parameters. In this the iterator can be string, bytes, tuple, list, or range and collection can be a dictionary, set, or frozen set.

Parameter Description Required / Optional
iterable  retrieves next item from the iterator Required
default  this value is returned if the iterator is exhausted optional

next() Return Value

If it reaches the end of the iterator and the default value is not specified, it will raise a StopIteration exception.

Input Return Value
 iterator next element from the iterator

Examples of next() method in Python

Example 1: How to get the next item


random = [5, 9, 'cat']

# converting the list to an 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 raise Error
# iterator is exhausted
print(next(random_iterator))
 

Output:


5
9
cat
Traceback (most recent call last):
  File "python", line 18, in 
StopIteration

Example 2: Passing default value to next()


random = [5, 9]

# converting the list to an 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:

5
9
-1
-1
-1

Example 3: Function throws an error when reaches the end of the collection


# Python next() function example  
number = iter([256, 32, 82]) # Creating iterator  
# Calling function  
item = next(number)   
# Displaying result  
print(item)  
# second item  
item = next(number)  
print(item)  
# third item  
item = next(number)  
print(item)  
# fourth item  
item = next(number) # error, no item is present  
print(item)  
 

Output:

Traceback (most recent call last): 
  File "source_file.py", line 14, in 
    item = next(number)
StopIteration 
256
32
82