iter()
The iter()
function returns an iterator object.
Syntax
iter(object, sentinel)
object
: A required object parameter. Theiter()
function returns an iterator object for this.sentinel
: An optional parameter. If set, the iterator will call the object with no arguments for each call to its__next__()
method. If the value returned is equal tosentinel
;StopIteration
will be raised, otherwise the value will be returned.
Example
The example below demonstrates how the iter()
function is used in a Python program:
# Create a listfruits = ["apple", "banana", "cherry"]# Get an iterator objectfruit_iter = iter(fruits)# Iterate over the list using the iteratorprint(next(fruit_iter))print(next(fruit_iter))print(next(fruit_iter))
In the code above a list is declared, and the iter()
function is used to get an iterator object for the list. Finally, the next()
function is used to step through the items in the list.
The output will be:
applebananacherry
Applying a Sentinel
The following example applies the optional sentinel
parameter through a callable class object (though the __call__()
method):
class Countdown:def __init__(self,start):self.start = startdef __iter__(self):return selfdef __next__(self):self.start -= 1return self.start__call__ = __next__my_iter = iter(Countdown(10), 0)for x in my_iter:print(x)
The output will be:
987654321
Codebyte Example
When using iterables, it usually isn’t necessary to call iter()
or deal with iterator objects. The for
loop does this automatically by creating a temporary, unnamed variable to hold the iterator for the duration of the loop.
The following code examples use the iter()
function and a for
loop to produce the same results:
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 Friendly90 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