Home

Iter

Iter is commonly used to refer to the Python built-in function iter, which returns an iterator for a given iterable. There are two forms: iter(iterable) and iter(callable, sentinel). The first creates an iterator from an iterable object by calling its __iter__ method. The second creates an iterator that repeatedly calls a zero-argument function until it returns a sentinel value; when the sentinel is produced, iteration ends.

An iterator implements the iteration protocol by providing __iter__ and __next__ methods. __iter__ returns the iterator

Common iterables include lists, tuples, strings, and dictionaries (which yield keys by default). You obtain an

Notes: The distinction between iterable and iterator is important. An iterable can produce a new iterator each

itself,
and
__next__
returns
the
next
value
or
raises
StopIteration
when
there
are
no
more
items.
Iterators
are
stateful,
advancing
through
a
sequence
as
next()
is
called.
The
underlying
object
is
typically
described
as
an
iterable
if
it
can
produce
an
iterator
via
__iter__
(or
support
indexed
access
via
__getitem__
in
older
designs).
iterator
with
iter(obj)
and
advance
it
with
next(it).
Most
high-level
constructs,
such
as
for
loops,
use
iterators
implicitly.
You
can
also
create
a
list
from
an
iterable
with
list(obj)
or
from
an
iterator
with
list(it).
When
exhausted,
subsequent
calls
to
next(it)
raise
StopIteration,
and
a
for
loop
ends
automatically.
time,
while
an
iterator
is
consumable
and
cannot
be
reset
unless
you
obtain
a
new
one
from
the
iterable.
Some
objects
are
both
iterable
and
iterators,
such
as
generator
objects
created
by
generator
expressions.