next()
The next()
function returns the next element from an iterator object.
Syntax
next(iterator_object, [default_parameter])
The 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_parameter
is returned. Without a setdefault_parameter
, aStopIteration
error is thrown.
Example
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 next()
function:
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:
Hi27Python10
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
for
loop. However, thefor
loop actually generates its own iterator object and applies thenext()
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)
Codebyte Example
This example iterates over the same list with the next()
function, but prevents the program from crashing with a default parameter:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly95 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours