len() — Advanced Playground
Returns the number of items in a container
Python Playground
# Custom __len__ implementation
class Playlist:
def __init__(self, songs):
self._songs = songs
def __len__(self):
return len(self._songs)
def __bool__(self):
return len(self) > 0
p = Playlist(["song1", "song2", "song3"])
print(len(p))
print(bool(p))
print(bool(Playlist([])))
Output
Click "Run" to execute your code
Understanding the dunder methods that len() calls helps you customize behavior for your own classes.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?