In Python, the iter() function has two core purposes: first, to obtain an iterator from an iterable object, and second, to dynamically generate an iterator based on a callable object.
Function Syntax
iter(iterable)
iter(callable, sentinel)
iter() has two usage patterns. With one parameter:
iterable: An iterable object.
Returns an iterator for this iterable object.
If an object is iterable, it implements the __iter__() method, which returns an iterator. The iterator returns elements one by one through the __next__() method and raises a StopIteration exception when exhausted.
With two parameters:
callable: A function or callable object.sentinel: Stops iteration when the callable returns this value.
With two parameters, iter() creates a new iterator. When the iterator's __next__() method is called, it invokes callable() and checks if the return value equals sentinel. If it does, StopIteration is raised; otherwise, the value is returned.
iter() Function Examples
This example demonstrates how iterators work:
class MyRange:
def __init__(self, start, stop):
self.current = start
self.stop = stop
def __iter__(self):
return self
def __next__(self):
if self.current >= self.stop:
raise StopIteration
value = self.current
self.current += 1
return value
# Use for loop to iterate
for num in MyRange(1, 5):
print(num)
Simple usage of iter() function:
# Define a list
my_list = [1, 2, 3]
# Get iterator for my_list
# Actually calls my_list.__iter__()
my_iterator = iter(my_list)
# Get next values from iterator sequentially
# Actually calls my_iterator.__next__()
print(next(my_iterator)) # Output: 1
print(next(my_iterator)) # Output: 2
print(next(my_iterator)) # Output: 3
# Getting next value again raises StopIteration
print(next(my_iterator)) # Raises StopIteration exception
for loops internally use iter():
lst = [1, 2, 3]
for item in lst:
print(item)
# Equivalent to
lst_iter = iter(lst)
while True:
try:
item = next(lst_iter)
print(item)
except StopIteration:
break
Using the iter(callable, sentinel) form:
import random
# Returns a random number between 0 and 100
def get_number():
return random.randint(0, 100)
# Create an iterator
# Each iteration value is generated by get_number
# Stops iteration when generated value is 0
num_iter = iter(get_number, 0)
for num in num_iter:
print(num)