AlgoViz

Iterator pattern

medium 45 min

The Iterator pattern gives access to the elements of a collection one after the other without showing how they are stored.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:34

See it run

Objects at run time: the collection stays still, the iterator moves.

Operations

Playlist

The music player plays four songs and never sees how they are stored.

Step 1 of 9

A playlist

playerMusicPlayerfavouritesPlaylist0Bohemian Rhap.1Hotel Calif.2Stairway3Imagine

Four songs. The player knows the playlist and nothing about its storage: an array, a linked list or a database.

Step 1: A playlist

class PlaylistIterator:    def __init__(self, songs):        self._songs = songs        self._position = 0    def has_next(self):        return self._position < len(self._songs)    def next(self):        if not self.has_next():            raise Exhausted("no more songs")        song = self._songs[self._position]        self._position += 1        return songiterator = playlist.create_iterator()while iterator.has_next():    song = iterator.next()    play(song)
Watch
position
Result
Four songs, then no

Position is the number of songs already handed out.

In the real world

The same iterator pattern doing real jobs. Pick one and step through it.

In order: left, node, right. The stack holds the nodes whose left side is being visited.

Step 1 of 6

Push the left edge

iteratorInOrderstack4 2 1givennone4Node2Node6Node1Node3Node

Start

4, 2 and 1 go on the stack. Three nodes, the height of the tree.

Step 1: Push the left edge

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • The position in the collection

    critical

    Two loops over one playlist share the position and steal songs from each other.

    Wrong
    class Playlist:    def next(self):        self._position += 1        return self._songs[self._position - 1]
    Right
    class Playlist:    def create_iterator(self):        return PlaylistIterator(self._songs)
  • has_next that moves

    critical

    Two questions in a row lose an element.

    Wrong
    def has_next(self):    self._position += 1    return self._position < len(self._songs)
    Right
    def has_next(self):    return self._position < len(self._songs)
  • Removing while looping

    critical

    Elements move, and some are skipped.

    Wrong
    for song in songs:    if song.old:        songs.remove(song)
    Right
    songs = [s for s in songs if not s.old]
  • Using one iterator twice

    major

    It is finished after the first loop. The second one is silently empty.

    Wrong
    walk = (s.seconds for s in songs)total = sum(walk)longest = max(walk)
    Right
    seconds = [s.seconds for s in songs]total = sum(seconds)longest = max(seconds)
  • Handing out the list itself

    major

    Callers depend on it and may change it.

    Wrong
    def songs(self):    return self._songs
    Right
    def __iter__(self):    return iter(self._songs)
  • Forgetting to close

    major

    A walk over a file that is left early keeps the file open.

    Wrong
    for line in lines(path):    if found(line):        break
    Right
    with closing(lines(path)) as walk:    for line in walk:        if found(line):            break

Interview tips

  • Two roles

    • The collection gives out iterators.
    • The iterator holds the position.
    • One iterator for one walk.
  • Small contract

    • More? changes nothing.
    • Next hands out and moves.
    • After the end, say so clearly.
  • Lazy

    • Fetch when asked.
    • Stop early for free.
    • Endless walks are allowed.
  • Say the policy

    • Fail fast, snapshot or weak.
    • Who closes?
    • Is the order promised?
  • Use the language

    • for loops call it for you.
    • Generators write it for you.
    • Build your own only when needed.