In Python, iter(iterable) returns an iterator: an object that hands out items one at a time when you call next() on it, and raises StopIteration when it runs out. A for loop calls iter() for you behind the scenes.
The second form, iter(callable, sentinel), calls a zero-argument function again and again and stops as soon as it returns the sentinel value. That is handy for reading a stream in chunks until it returns an empty string.
iter() is a built-in function: it lives in the builtins module, so it is always available without an import.
Syntax
Two forms: one argument, or a callable plus a sentinel.
An object with __iter__() (or __getitem__() starting at 0).
callable
Second form: a function with no arguments.
sentinel
Second form: iteration stops when callable() returns a value equal to this.
Return Value
Return Value
Description
iterator
An object that supports next().
Python Examples
Example 1 — Step Through a List by Hand
Get an iterator from a list, pull items with next(), and collect the rest.
python
colors = ["red", "green", "blue"]
it = iter(colors)
print(next(it))
print(next(it))
print(list(it))
print(iter(it) is it)
Output
red
green
['blue']
True
How It Works
A cursor.iter(colors) creates an iterator that remembers its position in the list.
One item per next(). The first two calls return red and green.
The rest.list(it) drains only what is left, so blue is the single item.
Iterators return themselves. Calling iter() on an iterator gives back the same object.
Example 2 — Read Chunks Until a Sentinel Value
Call a function repeatedly with the two-argument form and stop at a chosen value.
python
import io
from functools import partial
stream = io.StringIO("abcdefgh")
for chunk in iter(partial(stream.read, 3), ""):
print(repr(chunk))
rolls = iter([4, 2, 6, 1, 6, 3])
before_six = list(iter(lambda: next(rolls), 6))
print(before_six)
Output
'abc'
'def'
'gh'
[4, 2]
How It Works
A zero-argument callable.partial(stream.read, 3) is a function that reads three characters per call.
Stop on the sentinel. At the end of the text, read() returns "", which ends the loop.
Short last chunk. Only two characters remain for the last call, so the final chunk is 'gh'.
Sentinel not included. The roll list stops at the first 6 and that 6 is not part of the result.
Example 3 — Make a Reusable Iterable with __iter__
Write a class that returns a fresh generator from __iter__(), then try iter() on a number.
python
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
countdown = Countdown(3)
print(list(countdown))
print(list(countdown))
try:
iter(42)
except TypeError:
print("int is not iterable")
Output
[3, 2, 1]
[3, 2, 1]
int is not iterable
How It Works
__iter__ as a generator. Because __iter__ uses yield, each call returns a new generator.
Reusable. Each list(countdown) calls iter() again and gets a fresh iterator, so both lines match.
Generators stop cleanly. When the loop ends, the generator raises StopIteration and list() finishes.
Not iterable. An int has no __iter__, so iter(42) raises TypeError.
Frequently Asked Questions
An iterable can produce iterators (it has __iter__). An iterator is a one-pass object you call next() on; it is also iterable and returns itself.
It calls the function with no arguments until the result equals the sentinel, yielding each result before that.
Define __iter__ and return an iterator from it. Writing __iter__ as a generator with yield is the simplest way.
Iterators are exhausted after one pass. Call iter() on the original iterable, or store the items in a list.
When next() is called after the last item. for loops and list() catch it for you.