__len__

Dunder MethodPython 2.0+Intermediate

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

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

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.

Try in Playground

Tags

oopmagic-methodprotocolcore