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:

Signature

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.

#Initializing
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')
        break
    else:
        print(e)

Output

Delhi
Mumbai
Hyderabad
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.

#Initializing
s = "python"
d={"1":"One","2":"Two","3":"Three"}
#Converting to iterator
s=iter(s)
d=iter(d)
#Using next and printing
print("next string - ",(next(s)))
print("next dictionary element - ",(next(d)))

Output

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.

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

Output

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

Conclusion

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.

References

Happy Learning 🙂

Leave A Comment