__len__Easy Examples

Called by len(); returns the number of items in the object

Implementing __len__

Basic implementation of __len__ in a class.

python
class Playlist:
    def __init__(self, songs):
        self.songs = songs

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

p = Playlist(["song1", "song2", "song3"])
print(len(p))

__len__ called by len(); returns the number of items in the object. Implementing it lets you customize how Python interacts with your objects.

__len__ in action

Seeing __len__ called by Python's built-in operations.

python
# How Python calls __len__ automatically
class Demo:
    def __init__(self, value):
        self.value = value

    def __len__(self):
        print(f"__len__ was called!")
        return 1

d = Demo(42)
# This triggers __len__:
print(len(d))

Python automatically calls __len__ when you use the corresponding operator or function on your object.

Want to try these examples interactively?

Open Easy Playground