Python next() function
Python next() function
The next() function in Python retrieves the next item from the iterator.
Syntax
next(iterator[, default])
Parameter
iterable: It is a required parameter which represents an iterable object.
default: This parameter represents a default value to return if the iterable has reached to its end.
Return
This function returns the next item in an iterator.
Example 1
# Python program explaining # the next() function week_list = iter(["Monday", "Tuesday", "Wednesday","Thursday","Friday"]) val = next(week_list) print(val) val = next(week_list) print(val) val = next(week_list) print(val) val = next(week_list) print(val)
Output
Monday Tuesday Wednesday Thursday
Example 2
# Python program explaining
# the next() function
list_val = [11,12, 13, 14, 15]
# converting list to an iterator
list_val = iter(list_val)
print ("The contents of the list are:")
# using default
while (1) :
next_val = next(list_val,'end')
if next_val == 'end':
print ('No more data is present!')
break
else :
print (next_val)
Output
The contents of the list are: 11 12 13 14 15 No more data is present!
