Iterator Pattern
You have used iterators since your first for loop. When you write for song in playlist, the loop asks the
playlist for an object that hands out songs one at a time, and keeps asking it for the next one until it says
there are no more. The loop has no idea whether the songs sit in a list, in a tree, in a shuffled order or on a
server, one page at a time.
That object is the Iterator pattern: the knowledge of how to step through a collection lives in its own object, not in the collection and not in the code that loops. It matters in LLD interviews in two ways. You design collections that others walk (a playlist, a file tree, a feed), and interviewers often ask you to write an iterator directly: over a tree, over pages, over nested lists.
🔁 In one sentence: put the logic for stepping through a collection in a separate object with a "give me the next one" method, so callers can walk any collection the same way without knowing how it is stored, and several walks can run at once.
The Problem It Solves
Here is a music player that reaches into the playlist's list and does the stepping itself.
class Playlist:
def __init__(self) -> None:
self.songs: list[Song] = []
class Player:
def __init__(self, playlist: Playlist) -> None:
self.playlist = playlist
self.index = 0
self.shuffle = False
self.order: list[int] = [] # shuffled positions, used when shuffle is on
self.repeat = False
def next_song(self) -> Song | None:
songs = self.playlist.songs
if self.index >= len(songs):
if not self.repeat:
return None
self.index = 0
position = self.order[self.index] if self.shuffle else self.index
self.index += 1
return songs[position]
Now the app adds an "Up next" panel showing the next five songs, and the trouble starts.
The player knows how the playlist is stored. It indexes straight into songs. If the playlist moves to a
linked list to make reordering cheap, or starts loading songs from a server as needed, the player breaks.
The stepping logic gets copied. Shuffle order and repeat wrap-around live in Player. The "Up next" panel
needs the same rules, so it copies them, slightly differently. The car display copies them a third time. When
repeat changes ("repeat one song" is added), each copy has to be found and fixed.
There is only one position. self.index is the only cursor. If the "Up next" panel used next_song() to
look ahead, playback would skip five songs. Two walks over the same playlist at the same time need two separate
positions, and this design has room for one.
Changes during the walk are undefined. Removing a song shifts every index after it, so the song that plays next silently changes. Nobody decided whether that is correct; it is just what the indexes do.
⚠️ The smell to look for: one class indexing into another class's internal list, or the same loop-with-an-index logic copied into several callers. The collection is leaking how it is stored.