The next() is an inbuilt function in Python that is used to retrieve the next item from an iterator. In case, if an iterator reaches the end, it returns default value if available. In absence of default value, it will raise a StopIteration exception.

Python next Function:


The signature for the next() function is as shown below. Here, l stores the next element of an iterator.

l=next(iterator, default)

Parameters and return type

  • This method takes a mandatory parameter iterator from which we will retrieve an element. default is an optional parameter that specifies the default value when we reach the end of the iterator.
  • However, it returns the next element from an iterator. This will print the default value if no more elements are left. In absence of default value, it will raise the StopIteration exception.

Python Built-in Function next Examples:

Example 1: For example, let us initialize a list with city names. Thereafter, we will convert this list to iterator using iter function. Once the list gets converted, we can use the next method to retrieve the iterator till the end of the list. The code given below prints all the elements of the list.

city = ["Delhi","Mumbai", "Hyderabad"]
# converting list to iterator
city = iter(city) 
# Using next()
while (1):
    e = next(city, 'End of list')
    if e == 'End of list':
        print('List ended')


List ended

Example 2: In this example, we will take a string and a dictionary. In the next step, we have to convert this string and dictionary to an iterator object. Thereafter, we can call next to print the next value of the string and dictionary.

s = "python"
#Converting to iterator
#Using next and printing
print("next string - ",(next(s)))
print("next dictionary element - ",(next(d)))


next string -  p
next dictionary -  1

Example 3: In this case, let us take a set containing string. As we know that set stores elements in any random order. Each time we execute, we will get different outputs.

city={"chennai", "delhi","mumbai", "hyderabad"}
# Printing set
#Converting to iterator and Using next 
print("Next value is ",next(city))


{'delhi', 'chennai', 'mumbai', 'hyderabad'}
Next value is delhi


The next() function returns the next element from an iterator. However, when it reaches an end of iterator, it either prints the default value or raises an exception.


Happy Learning 🙂