Make a Playlist Feel Like a List

Medium ⏱ 12 min 56% acceptance ★★★★★ 4.5
Wrap a list of song titles in a Playlist class implementing __len__ and __getitem__ so len(p), p[0], negative indexing and even for song in p all work — implementing __getitem__ alone is enough to make an object iterable.

Examples

Example 1
Input
p = Playlist(['a', 'b']); (len(p), p[-1])
Output
(2, 'b')
Explanation

Both dunders delegate to the wrapped list.

Constraints

  • Store the songs list internally.
  • Delegate, do not reimplement indexing math.

Topics

OOP__len__ and __getitem__

Companies

SpotifyNetflixApple

Hints

Hint 1

return self._songs[index] handles negatives free of charge.

Hint 2

Iteration falls back to __getitem__ with 0, 1, 2, …

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.