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:
All contributors
- THE-Spellchecker154 total contributions
- nikolaspoczekaj19 total contributions
- Anonymous contributorAnonymous contributor1 total contribution
- THE-Spellchecker
- nikolaspoczekaj
- Anonymous contributor
Looking to contribute?
- 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.