Python next() function
The next() function in Python retrieves the next item from the iterator.
Syntax
1 2 3 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# 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
1 2 3 4 5 6 |
Monday Tuesday Wednesday Thursday |
Example 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# 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
1 2 3 4 5 6 7 8 9 |
The contents of the list are: 11 12 13 14 15 No more data is present! |