next() function returns the next element from an iterator object.
iterator_object is required. The
default_parameter is optional and is printed if the end of the iterator is reached.
Note: If the next element is missing from the object, the
default_parameteris returned. Without a set
StopIterationerror is thrown.
In this example, a list called
list_items is converted to an iterable object via the
iter() function, and each element is printed by means of the
list_items = iter(["Hi", 27, "Python", 10])print(next(list_items))print(next(list_items))print(next(list_items))print(next(list_items))
This outputs the following:
If one more
print() runs without the default parameter, an
StopIteration error will be thrown:
Traceback (most recent call last):File "main.py", line 6, in <module>print(next(list_items))StopIteration
Note: This can also be done with a
forloop. However, the
forloop actually generates its own iterator object and applies the
next()function between each element. Since there is no risk of overflowing the list, a default parameter is not needed:list_items = iter(["Hi", 27, "Python", 10])for item in list_items:print(item)
This example iterates over the same list with the
next() function, but prevents the program from crashing with a default parameter:
- Anonymous contributor
Learn Python on Codecademy
Data Scientist: Machine Learning SpecialistMachine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Anonymous contributorAnonymous contributor