Home

Iterators

An iterator is an object that yields elements of a sequence one at a time. An iterable is an object that can produce an iterator. The iterator maintains internal state and, on each request, returns the next element until the sequence is exhausted. Once exhausted, subsequent requests are handled differently depending on the language, such as signaling termination or raising a specific exception.

In many languages, the interface and conventions differ. Python, for example, uses an iterator protocol where

Key features of iterators include lazy evaluation, meaning elements are produced only as needed, and memory

Common caveats include that many iterators are single-pass: once exhausted, they may not be reset without recreating

an
object
provides
a
__iter__
method
to
return
an
iterator
and
a
__next__
method
to
produce
the
next
value,
raising
StopIteration
when
the
end
is
reached.
Java
exposes
an
Iterator
interface
with
hasNext
and
next
methods.
C++
relies
on
iterator
objects
that
act
like
pointers,
advancing
with
increment
operations
and
dereferencing
to
access
elements.
Rust
defines
an
Iterator
trait
with
a
next
method
that
returns
an
optional
value.
Despite
syntax
differences,
the
core
idea
is
the
same:
a
stateful
provider
that
advances
through
elements
on
demand.
efficiency,
which
enables
working
with
large
or
infinite
sequences.
Iterators
are
composable
through
higher-order
operations
such
as
map,
filter,
and
zip,
enabling
pipelines
for
data
processing
without
materializing
intermediate
results.
the
underlying
iterable.
Understanding
the
distinction
between
iterables
and
iterators
helps
in
writing
efficient,
reusable
data-processing
code.