Home

Iterator

An iterator is an object that enables a programmer to traverse a sequence of elements, one at a time, without exposing the underlying structure. In common usage, an iterable is a collection or generator that can produce an iterator. An iterator maintains internal state about the current position and advances to the next element upon request.

Most languages separate the notions of iterable and iterator. An iterator exposes a method to return the

Iterators enable lazy evaluation: elements are produced on demand, which makes them suitable for large or infinite

Common considerations: most iterators are single-pass; restarting requires acquiring a new iterator. Iteration may have side

Applications include traversing lists, files, streams, or any data source that can be consumed sequentially. Iterators

next
element
and
to
detect
completion.
When
no
more
elements
exist,
iteration
ends.
In
Python,
an
iterator
implements
__iter__
(returning
self)
and
__next__
(raising
StopIteration).
In
Java,
the
Iterator
interface
provides
hasNext
and
next;
Java
8
adds
forEachRemaining.
In
C#,
IEnumerator
provides
MoveNext
and
Current,
and
IEnumerable
enables
obtaining
an
enumerator.
sequences.
They
support
memory-efficient
processing
and
can
be
composed
in
pipelines
via
map,
filter,
and
reduce
operations.
effects
or
depend
on
external
state.
Some
iterators
may
raise
exceptions
when
exhausted
or
when
the
source
changes
during
iteration.
underpin
language
constructs
such
as
for
loops
and
comprehensions,
and
enable
patterns
like
generator
functions
and
lazy
pipelines.