Iterator pattern
medium 45 minThe 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
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
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
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
criticalTwo loops over one playlist share the position and steal songs from each other.
Wrongclass Playlist: def next(self): self._position += 1 return self._songs[self._position - 1]Rightclass Playlist: def create_iterator(self): return PlaylistIterator(self._songs)has_next that moves
criticalTwo questions in a row lose an element.
Wrongdef has_next(self): self._position += 1 return self._position < len(self._songs)Rightdef has_next(self): return self._position < len(self._songs)Removing while looping
criticalElements move, and some are skipped.
Wrongfor song in songs: if song.old: songs.remove(song)Rightsongs = [s for s in songs if not s.old]Using one iterator twice
majorIt is finished after the first loop. The second one is silently empty.
Wrongwalk = (s.seconds for s in songs)total = sum(walk)longest = max(walk)Rightseconds = [s.seconds for s in songs]total = sum(seconds)longest = max(seconds)Handing out the list itself
majorCallers depend on it and may change it.
Wrongdef songs(self): return self._songsRightdef __iter__(self): return iter(self._songs)Forgetting to close
majorA walk over a file that is left early keeps the file open.
Wrongfor line in lines(path): if found(line): breakRightwith 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.