Python 3 reference · Built-in Functions

Python iter() Function

Get an iterator from an iterable, or create one that calls a function until it returns a sentinel value.

Python 3 Since 3.0

Syntax

iter(iterable)
iter(callable, sentinel)

Parameters

ParameterDescription
iterable Any iterable.
callable, sentinel optional Call callable() repeatedly until it returns sentinel.

Return value

An iterator.

Examples

Iterate by handTry it yourself
it = iter([10, 20, 30])
print(next(it), next(it), next(it))
print(next(it, "no more"))

Output

10 20 30
no more
Read in chunks until the endTry it yourself
import io
stream = io.StringIO("abcdefgh")
for chunk in iter(lambda: stream.read(3), ""):
    print(chunk)

Output

abc
def
gh

Good to know

An iterator can be used once: after it is exhausted, it stays empty. Call iter() on the original iterable again to start over.

Version history

VersionChange
Python 3.0Added