iter()
iter(object[, sentinel]) Returns:
iterator · Updated March 13, 2026 · Built-in Functions built-in iteration iterator sentinel
The iter() function returns an iterator object from an iterable. It is the standard way to obtain an iterator in Python, converting any iterable into an object that can be traversed one element at a time using next().
Syntax
iter(object[, sentinel])
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| object | iterable or callable | — | An iterable to convert to an iterator, or a callable to call repeatedly |
| sentinel | any | — | If provided, object must be a callable. iter() calls object() repeatedly until the sentinel value is returned |
Examples
Basic usage with an iterable
my_list = [1, 2, 3]
my_iter = iter(my_list)
print(next(my_iter))
# 1
print(next(my_iter))
# 2
print(next(my_iter))
# 3
Using iter() with a string
text = "hello"
char_iter = iter(text)
print(next(char_iter))
# h
print(next(char_iter))
# e
Using iter() with a sentinel value
The two-argument form of iter() is powerful for creating custom iterators from callable functions:
class LineReader:
def __init__(self, lines):
self.lines = lines
self.index = 0
def __call__(self):
if self.index >= len(self.lines):
return ""
line = self.lines[self.index]
self.index += 1
return line
lines = ["line 1", "line 2", ""]
reader = LineReader(lines)
for line in iter(reader, ""):
print(line)
# line 1
# line 2
Creating an iterator from a callable
import random
def dice_roller():
return random.randint(1, 6)
for roll in iter(dice_roller, 6):
print(f"Rolled: {roll}")
Common Patterns
Reading file contents line by line
with open("data.txt") as f:
for line in iter(f.readline, ""):
if line.strip():
print(line.strip())
This pattern reads lines until an empty string is returned.
Using iter() with class objects
class Counter:
def __init__(self, limit):
self.current = 0
self.limit = limit
def __iter__(self):
return self
def __next__(self):
if self.current >= self.limit:
raise StopIteration
self.current += 1
return self.current - 1
for num in iter(Counter(5)):
print(num)
# 0
# 1
# 2
# 3
# 4
Error Handling
TypeError: object is not iterable
iter(123)
# TypeError: object is not iterable
TypeError: iter() with sentinel requires a callable
iter([1, 2, 3], 5)
# TypeError: iter() with sentinel requires a callable
See Also
- built-in::next — retrieve the next item from an iterator
- built-in::enumerate — iterate with index and value pairs
- built-in::zip — iterate over multiple iterables in parallel
- itertools — module with advanced iterator tools