Hard: Advanced Interview · Problem 72 of 82

A Playlist Container

HardClassesPython

Write a class Playlist(songs=None) that holds song names and behaves like a sequence:

  • add(song) appends a song.
  • len(p) gives the number of songs; p[i] gives a song (negative indexes work); p[a:b] gives a list of songs.
  • for song in p loops over the songs in order, and "x" in p tests membership.
  • p + q gives a new Playlist with the songs of both; adding anything else raises TypeError.
  • The list you pass in is copied: changing it later must not change the playlist.

Understand the problem

Match each behaviour to its special method.

Which special method does p[2] call?

  1. __index__
  2. __getitem__
  3. __get__

p[key] calls p.__getitem__(key). The key can be an integer or a slice object (for p[1:3]), so the method must handle both.

A class defines only __len__ and __getitem__ (with integer indexes). Which of these then works without extra code?

  1. for song in p
  2. None of them
  3. p + q

Python falls back to calling __getitem__(0), __getitem__(1), ... until IndexError, so a class with __getitem__ is already iterable, and in works the same way. It is the old iteration protocol; the modern way is __iter__.

Write the solution

Write the class.

class Playlist:
    # Write your code here.
    pass
Hint 1: a question to ask yourself

If the class keeps its songs in a list, which operations can simply be passed on to that list?

Hint 2: the shape of the answer

Store self._songs = list(songs or []) (this also copies). __len__, __getitem__ and __iter__ can return the list's own. __add__ checks the type and builds a new Playlist.

Reflect

Solution

class Playlist:
    def __init__(self, songs=None):
        self._songs = list(songs or [])

    def add(self, song):
        self._songs.append(song)

    def __len__(self):
        return len(self._songs)

    def __getitem__(self, index):
        return self._songs[index]

    def __iter__(self):
        return iter(self._songs)

    def __contains__(self, song):
        return song in self._songs

    def __add__(self, other):
        if not isinstance(other, Playlist):
            return NotImplemented
        return Playlist(self._songs + other._songs)

Another way: inherit from collections.abc.Sequence

from collections.abc import Sequence

class Playlist(Sequence):
    def __init__(self, songs=None):
        self._songs = list(songs or [])

    def add(self, song):
        self._songs.append(song)

    def __len__(self):
        return len(self._songs)

    def __getitem__(self, index):
        return self._songs[index]

    def __add__(self, other):
        if not isinstance(other, Playlist):
            return NotImplemented
        return Playlist(self._songs + other._songs)

What this tests: __len__, __getitem__ (with slices), __iter__, __contains__, __add__, copying a mutable argument, and delegating to an internal list.

Slices are objects: p[1:3] calls __getitem__(slice(1, 3)). Passing the key straight to the inner list handles ints, negatives and slices at once.

Copy mutable arguments: list(songs or []) makes a private copy. Without it, the caller could change the playlist by changing their list, and Playlist() with a mutable default would share one list between instances.

collections.abc.Sequence gives you __iter__, __contains__, index, count and __reversed__ for free once you provide __len__ and __getitem__. In real code that is the cleanest start.

What an interviewer might ask next: Add __eq__ so that two playlists with the same songs are equal, and __repr__. (And __hash__ only if the playlist cannot change.)