Skip to content

Iterator Pattern: Walk Any Collection Without Knowing Its Shape

Learn the Iterator pattern with a bike-share example: traverse ring buffers and paged archives uniformly, using generators for lazy sequences.

14 min readDesign patternBehavioural

Provide a way to access the elements of a collection sequentially without exposing its internal representation, so that clients can traverse different collections through one uniform interface and multiple traversals can run independently.

Iterator is the pattern you already use every time you write a for loop over something that isn't a plain array. It separates the question of how data is stored from the question of how you walk through it. In interviews it shows up in two ways: as a classic GoF design question (who owns the cursor, what happens if the collection changes mid-walk) and as a practical one (build a lazy paginated reader, flatten a nested structure, implement hasNext/next). This guide uses one scenario throughout: a bike-share operator whose trip data lives in a ring buffer on each dock and in a paged archive API, and a reporting job that should not care which is which.

The problem

A situation where the obvious design starts to hurt.

Spokewise runs a bike-share network with 1,200 bikes and 140 docks. Each dock's controller keeps its most recent 500 trips in a fixed-size ring buffer: new trips overwrite the oldest slot, and a head index marks where the next write goes. Older trips live in an archive service that returns 200 trips per page.

The analytics team writes reports against both sources: total fares for the day, the first trip over 40 minutes, refunds to review. Every report started with two copies of the same loop. One computed (head - size + capacity) % capacity and walked the slots with a modulo. The other tracked a page number, called the archive, checked for an empty page and looped again.

Three things went wrong. A new analyst forgot the modulo and read stale slots, double-counting fares. The archive loop always fetched every page, even for "find the first long trip" queries that could stop after the second page, so a report that needed 400 trips pulled tens of thousands. And when the dock team changed the buffer to store trips newest-first, every report broke, because every report knew the buffer's layout.

The solution

What the pattern proposes.

Give each collection the responsibility of producing an iterator: a small object that knows how to walk that particular structure and exposes only "give me the next trip, or tell me you're done".

RecentTrips returns a RecentTripsIterator that holds the start index and a count of visited slots. The modulo arithmetic lives in exactly one place. TripArchive returns a generator: a function that fetches page 0, yields its trips one at a time, and only fetches page 1 when the consumer asks for the trip after the last one on page 0. If the consumer stops early, no further pages are requested. That is a lazy sequence: elements are produced on demand, not up front.

Both collections implement the language's iterable protocol (Symbol.iterator in TypeScript, __iter__ in Python, IteratorAggregate in PHP). Report functions such as totalFareCents and firstLongTrip accept any iterable of trips and use a plain for loop. They no longer know about slots, heads, pages or HTTP. When the dock team changes the buffer layout, they change one iterator and every report keeps working.

An everyday analogy

The same idea, outside software.

Think of a hotel guest asking the front desk for wake-up calls in room order. The night porter doesn't hand over the booking ledger, the overflow sheet from the annex and the sticky notes on the board. He just knocks on doors one after another: "next room". Behind the scenes he might be reading from three different lists, and he only walks to the annex when he has finished the main building. If the manager says "stop after the first guest who wants coffee", he stops there and never climbs the annex stairs. The guests, like your report code, only ever see the next door.

Structure

The pieces and how they relate.

Two collections with different internal layouts each create their own iterator; the report depends only on the iterable and iterator interfaces.RecentTrips implements Iterable<Trip>. TripArchive implements Iterable<Trip>. RecentTripsIterator implements Iterator<Trip>. Archive generator implements Iterator<Trip>. RecentTrips creates RecentTripsIterator. TripArchive creates Archive generator. FareReport calls Iterable<Trip> (asks for iterator). FareReport calls Iterator<Trip> (next()).«interface»Iterable<Trip>[Symbol.iterator]():Iterator<Trip>«interface»Iterator<Trip>next(): {value,done}RecentTripsring buffer: slots,head, sizeTripArchivefetchPage(page),pagesFetchedRecentTripsIteratorstart, visited,countArchive generatorfetches next page ondemandFareReporttotalFareCents,firstLongTripLazystopping early meansno more pagesasks for iteratornext()
Two collections with different internal layouts each create their own iterator; the report depends only on the iterable and iterator interfaces.

Participants

Iterator (Iterator<Trip>)
Declares the traversal operation: return the next element or signal that the sequence is finished. In the three languages here this is the built-in protocol, so for loops, spread and comprehensions work automatically.
Concrete Iterator (RecentTripsIterator, archive generator)
Holds the traversal state for one walk: a position, a count, the current page. Knows the collection's layout so the client doesn't have to. Each call to the collection gives a fresh one, so two walks never share a cursor.
Iterable Collection (Iterable<Trip>)
Declares the factory method that returns an iterator. It is the only thing a client needs to accept.
Concrete Collection (RecentTrips, TripArchive)
Stores the data in whatever shape suits it, a ring buffer or a remote paged API, and returns the matching concrete iterator.
Client (FareReport)
Works with any iterable of trips through a plain loop. It can stop early, and with a lazy iterator stopping early also stops the work of producing elements.

Pseudocode

The solution to the scenario, language-neutral.

interface Iterator<T>
    method next(): (value: T, done: bool)

interface Iterable<T>
    method iterator(): Iterator<T>

class RecentTrips implements Iterable<Trip>
    field slots: array of Trip, length = capacity
    field head = 0      // next write position
    field size = 0

    method add(trip)
        slots[head] = trip
        head = (head + 1) mod capacity
        if size < capacity then size = size + 1

    method iterator()
        start = (head - size + capacity) mod capacity
        return new RecentTripsIterator(slots, start, size)

class RecentTripsIterator implements Iterator<Trip>
    field visited = 0
    method next()
        if visited >= count then return (none, done = true)
        trip = slots[(start + visited) mod length(slots)]
        visited = visited + 1
        return (trip, done = false)

class TripArchive implements Iterable<Trip>
    field fetchPage: function(page) -> list of Trip
    field pagesFetched = 0

    generator method iterator()
        page = 0
        loop
            trips = fetchPage(page)
            pagesFetched = pagesFetched + 1
            if trips is empty then return
            for each trip in trips
                yield trip       // suspends here until the caller asks again
            page = page + 1

function firstLongTrip(trips: Iterable<Trip>, minMinutes)
    for each trip in trips
        if trip.minutes >= minMinutes then return trip
    return none

function totalFareCents(trips: Iterable<Trip>)
    sum = 0
    for each trip in trips
        sum = sum + trip.fareCents
    return sum

The code

The same solution in TypeScript, Python and PHP.

interface Trip {
  id: string;
  minutes: number;
  fareCents: number;
}

class RecentTripsIterator implements Iterator<Trip> {
  private visited = 0;

  constructor(
    private readonly slots: (Trip | undefined)[],
    private readonly start: number,
    private readonly count: number,
  ) {}

  next(): IteratorResult<Trip> {
    if (this.visited >= this.count) {
      return { done: true, value: undefined };
    }
    const trip = this.slots[(this.start + this.visited) % this.slots.length] as Trip;
    this.visited++;
    return { done: false, value: trip };
  }
}

class RecentTrips implements Iterable<Trip> {
  private readonly slots: (Trip | undefined)[];
  private head = 0;
  private size = 0;

  constructor(private readonly capacity: number) {
    this.slots = new Array(capacity).fill(undefined);
  }

  add(trip: Trip): void {
    this.slots[this.head] = trip;
    this.head = (this.head + 1) % this.capacity;
    if (this.size < this.capacity) this.size++;
  }

  [Symbol.iterator](): Iterator<Trip> {
    const start = (this.head - this.size + this.capacity) % this.capacity;
    return new RecentTripsIterator(this.slots, start, this.size);
  }
}

type PageFetcher = (page: number) => Trip[];

class TripArchive implements Iterable<Trip> {
  pagesFetched = 0;

  constructor(private readonly fetchPage: PageFetcher) {}

  *[Symbol.iterator](): Generator<Trip> {
    for (let page = 0; ; page++) {
      const trips = this.fetchPage(page);
      this.pagesFetched++;
      if (trips.length === 0) return;
      for (const trip of trips) {
        yield trip;
      }
    }
  }
}

function totalFareCents(trips: Iterable<Trip>): number {
  let sum = 0;
  for (const trip of trips) sum += trip.fareCents;
  return sum;
}

function firstLongTrip(trips: Iterable<Trip>, minMinutes: number): Trip | undefined {
  for (const trip of trips) {
    if (trip.minutes >= minMinutes) return trip;
  }
  return undefined;
}

// Dock buffer with capacity 3: T1 gets overwritten by T4.
const recent = new RecentTrips(3);
recent.add({ id: "T1", minutes: 12, fareCents: 350 });
recent.add({ id: "T2", minutes: 45, fareCents: 900 });
recent.add({ id: "T3", minutes: 8, fareCents: 250 });
recent.add({ id: "T4", minutes: 30, fareCents: 700 });
console.log([...recent].map((t) => t.id).join(",")); // T2,T3,T4
console.log(totalFareCents(recent)); // 1850

// Archive served 2 trips per page.
const archiveData: Trip[] = [
  { id: "A1", minutes: 10, fareCents: 300 },
  { id: "A2", minutes: 15, fareCents: 400 },
  { id: "A3", minutes: 50, fareCents: 1100 },
  { id: "A4", minutes: 20, fareCents: 500 },
  { id: "A5", minutes: 5, fareCents: 200 },
  { id: "A6", minutes: 60, fareCents: 1300 },
];
const archive = new TripArchive((page) => archiveData.slice(page * 2, page * 2 + 2));
const long = firstLongTrip(archive, 40);
console.log(long?.id, archive.pagesFetched); // A3 2

When to use it

Situations where it pays off.

  • Your collection has a non-trivial internal layout (ring buffer, tree, hash buckets, linked chunks) and you don't want callers to depend on it.

    The traversal logic is written once inside the iterator. Changing the layout means changing one class, not every loop in the codebase, which is exactly what broke Spokewise's reports when the buffer order changed.

  • You need one piece of code to walk several different data sources the same way.

    Accepting an iterable instead of an array or a specific class lets totalFareCents run over the dock buffer, the archive, a test fixture or a filtered view without overloads or type checks.

  • Elements are expensive to produce or the sequence is large or unbounded: paged APIs, database cursors, log files, generated IDs.

    A generator yields elements on demand. Memory stays at one page instead of the whole result, and a consumer that stops early never triggers the remaining fetches.

  • You need several independent traversals at once, or different traversal orders over the same data.

    Each iterator carries its own cursor, so two reports can walk the same buffer concurrently in a single thread without interfering, and you can add a newest-first iterator without touching the collection's storage.

How to implement it

Steps to introduce it in existing code.

  1. Define what a single step returns. In TypeScript, Python and PHP, reuse the built-in iterator protocol rather than inventing hasNext/next methods, so the language's loops and helpers work with your collection.

  2. Make the collection iterable: add [Symbol.iterator](), __iter__ or getIterator() that returns a fresh iterator on every call. Never store the cursor on the collection itself.

  3. For structures with tricky index math, write an explicit iterator class that holds the start position and a visited counter, and keep all the arithmetic inside it.

  4. For sequences produced in steps (pages, chunks, lines), write the iterator as a generator. Fetch one unit, yield its elements one by one, then fetch the next unit only when the loop resumes.

  5. Change client code to accept the iterable interface rather than a concrete collection or array, and replace hand-written index loops with plain for loops.

  6. Decide and document what happens if the collection is modified mid-iteration: snapshot, fail fast with an error, or allow it with undefined ordering. Test that behaviour.

  7. Add a test that proves laziness, for example by counting page fetches when the consumer stops early.

Pros and cons

What you gain and what you pay.

Pros

  • Single Responsibility: traversal logic moves out of every caller and into one place per collection.
  • Open/Closed: you can add new collections or new traversal orders without changing client code.
  • Each iterator has its own state, so multiple traversals over the same collection can run independently.
  • Generators make lazy sequences cheap to write: memory stays bounded and work stops when the consumer stops.
  • Clients get the full power of the language's iteration tools (spread, comprehensions, iterator_to_array, pipelines) for free.

Cons

  • For a plain array that will never change shape, a custom iterator adds a class and indirection with no benefit.
  • Iterators are usually single-pass and forward-only; a consumer that needs random access or the length must materialise the sequence, losing laziness.
  • Lazy sequences defer errors and side effects: a network failure on page 7 surfaces in the middle of a report loop, far from where the archive was constructed.
  • Modifying a collection while iterating it is easy to get wrong, and the safe options (snapshots, version counters) cost memory or checks.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

What is the difference between an iterable and an iterator?

An iterable is something you can ask for an iterator: the collection, with [Symbol.iterator](), __iter__ or getIterator(). An iterator is the cursor for one walk, with next() or __next__. Keeping them separate is what allows two independent loops over the same RecentTrips. A common interview bug is making the collection its own iterator, which means a second loop starts where the first one stopped.

When should I write a generator instead of an explicit iterator class?

Use a generator when the traversal is naturally a loop with some local state, like fetching pages or walking a tree recursively; the language keeps the state for you between yields. Use an explicit class when you need extra methods on the iterator (peek, remaining count, position for checkpointing) or when the state is simple index arithmetic you want to make obvious and testable.

How do generators make a sequence lazy, and what does that cost?

A generator runs until it hits yield, hands back one value and suspends. Nothing after that runs until the consumer asks for the next value. In the example, firstLongTrip returns at A3, so page 2 is never fetched and memory holds at most one page. The costs are single-pass consumption (you can't rewind a generator in TypeScript or Python, and PHP throws if you rewind one that has advanced) and deferred errors that appear mid-loop.

What happens if the collection changes while I'm iterating?

It depends on the design, and you should say which you chose. In the TypeScript and Python examples the iterator reads the live slots array, so an add during a walk can return a newer trip in place of an older one. PHP arrays are copied on write, so the PHP iterator sees a snapshot. Other options are a modification counter that makes the iterator throw on change, as Java collections do, or explicit copying in getIterator().

Is Iterator still relevant when every modern language has for-each loops?

Yes, because for-each is the pattern built into the language. The protocol is standard, but you still write the concrete iterators for your own structures: ring buffers, paged APIs, database cursors, trees. Interviewers test this with problems like implementing a peeking iterator, flattening nested lists lazily, or reading a paginated endpoint without loading everything.

What is the time and space complexity of these iterators?

RecentTripsIterator.next() is O(1) time and the iterator uses O(1) extra space. A full walk of the buffer is O(n). The archive generator does O(1) work per element plus one page fetch every 200 elements in production (2 in the demo), and holds O(page size) memory regardless of how many trips the archive contains.

Next guide4 of 10 · Behavioral patternsMediator: Route Component Chatter Through One CoordinatorRead the next one