☼
⌃
☰

Iterators

Table of Contents

A standardised interface for traversing a sequence of elements one at a time, without exposing the underlying data structure. Decouples traversal logic from the collection itself — the same code that iterates a list works on a database cursor, a file, or a network stream.

Related: Functional Programming Python Functions Software Design Patterns

The Iterator Protocol

Two concepts, often conflated:

Concept What it is
Iterable An object that can produce an iterator (a list, a file, a range)
Iterator A stateful object that tracks position and returns the next element

An iterable produces an iterator on demand. The iterator is consumed once — it moves forward only.

Python

Built-in protocol

PYTHON
# iter() creates an iterator from an iterable
# next() advances it

my_list = [10, 20, 30]
it = iter(my_list)

next(it)   # 10
next(it)   # 20
next(it)   # 30
next(it)   # raises StopIteration

# for loops do this automatically
for x in my_list:
    print(x)
# equivalent to:
it = iter(my_list)
while True:
    try:
        x = next(it)
        print(x)
    except StopIteration:
        break

Implementing a custom iterator

PYTHON
class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self           # the object is its own iterator

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

for n in Countdown(3):
    print(n)   # 3, 2, 1

Generators — the easy way

A function with yield creates an iterator automatically. State is preserved between calls. No class boilerplate needed.

PYTHON
def countdown(start):
    while start > 0:
        yield start
        start -= 1

for n in countdown(3):
    print(n)   # 3, 2, 1

# Generator expressions (lazy list comprehension)
squares = (x**2 for x in range(10))   # nothing computed yet
next(squares)   # 0 — computed on demand

Memory efficiency — infinite sequences

PYTHON
def integers_from(n):
    while True:
        yield n
        n += 1

# Generate as many as you need without storing them all
gen = integers_from(0)
[next(gen) for _ in range(5)]   # [0, 1, 2, 3, 4]

# itertools for common patterns
import itertools

itertools.count(0)             # 0, 1, 2, 3... (infinite)
itertools.cycle([1, 2, 3])     # 1, 2, 3, 1, 2, 3... (infinite)
itertools.islice(gen, 5)       # take first 5 from any iterator
itertools.chain(a, b)          # concatenate two iterables lazily

Common iterator patterns

PYTHON
# enumerate — index + value
for i, item in enumerate(["a", "b", "c"]):
    print(i, item)   # 0 a, 1 b, 2 c

# zip — parallel iteration
for a, b in zip([1, 2, 3], ["x", "y", "z"]):
    print(a, b)   # 1 x, 2 y, 3 z

# map/filter — lazy transformation
doubled = map(lambda x: x * 2, range(5))   # lazy
evens   = filter(lambda x: x % 2 == 0, range(10))

# Materialise when needed
list(doubled)   # [0, 2, 4, 6, 8]

JavaScript

JAVASCRIPT
// for...of uses the iterator protocol automatically
const arr = ["apple", "banana", "cherry"];
for (const item of arr) {
    console.log(item);
}

// Manual use of the iterator protocol
const it = arr[Symbol.iterator]();
it.next();   // {value: "apple", done: false}
it.next();   // {value: "banana", done: false}
it.next();   // {value: "cherry", done: false}
it.next();   // {value: undefined, done: true}

// Custom iterator
function range(start, end) {
    return {
        [Symbol.iterator]() {
            let current = start;
            return {
                next() {
                    return current < end
                        ? { value: current++, done: false }
                        : { value: undefined, done: true };
                }
            };
        }
    };
}

for (const n of range(1, 4)) console.log(n);   // 1, 2, 3

// Generators in JS
function* countdown(n) {
    while (n > 0) yield n--;
}

[...countdown(3)]   // [3, 2, 1]

Tips

  • Prefer generators over manual iterator classes in Python — they are shorter, clearer, and automatically handle StopIteration
  • Generator expressions are the lazy equivalent of list comprehensions — use them when you only need to iterate once and don't need random access
  • Iterators are consumed once — if you need to iterate multiple times, convert to a list first or recreate the iterator
  • itertools is the standard library for composing iterators; know chain, islice, zip_longest, groupby, and product