A Custom Container
Completed
Create Playlist that stores songs and supports len(), indexing (p[0]), in and iteration. Read songs, then a song to look for; print the length, the first and last song, whether the searched song is in the playlist, and all songs numbered.
Input
Line 1: songs separated by commas. Line 2: a song title.
Output
Several lines.
Example
Input
Yellow, Clocks, Fix You Clocks
Output
3 Yellow Fix You True 1. Yellow 2. Clocks 3. Fix You
Editor
Python
Hints
__getitem__ powers p[i]; __contains__ powers in; __iter__ powers for loops.
Solution explanation
Implementing these methods makes your class behave like a built-in sequence.
Show solution
class Playlist:
def __init__(self, songs):
self._songs = list(songs)
def __len__(self):
return len(self._songs)
def __getitem__(self, index):
return self._songs[index]
def __contains__(self, song):
return song in self._songs
def __iter__(self):
return iter(self._songs)
p = Playlist(s.strip() for s in input().split(","))
wanted = input()
print(len(p))
print(p[0])
print(p[-1])
print(wanted in p)
for i, song in enumerate(p, 1):
print(f"{i}. {song}")