len()Advanced Examples

Returns the number of items in a container

len() protocol implementation

Implementing the protocol that len() uses under the hood.

python
# 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([])))

Understanding the dunder methods that len() calls helps you customize behavior for your own classes.

Edge cases with len()

Handling unusual inputs and edge cases.

python
# len() edge cases
print("Edge case handling for len()")

# Type checking
print(type("test"))

Knowing these edge cases prevents subtle bugs in production.

Want to try these examples interactively?

Open Advanced Playground