The __len__() method allows objects to define a value that will be returned when we call the builtin len() function on the object.  When len() function is called, it literally in turn calls the __len__() method. 

The method belongs to a set of methods known as the dunder(double underscore) or magic methods. Traditionally, it is defined by compound objects i.e objects made up of more than one elements. It is used to find number of elements in the object.

L = [1, 2, 3, 4, 5]
print(len(L))

print(L.__len__())
#len with strings

print(len("Python Programming"))

print("Python Programming".__len__())

__len__() Method with custom classes

Defining the __len__() method on custom classes makes it possible to use the builtin  len() function with the class objects.  The method must strictly return an integer value, Otherwise an error will be raised if the len() function is called on the object.

class CustomList():
    def __init__(self, elements=[]): 
        self.elements = elements
     
    #Define the __len__ method
    def __len__(self):
        return len(self.elements)

test_list = CustomList(elements=[1, 2, 3, 4, 5])

print(len(test_list))

Like in all other instance methods, the self parameter must be specified in the __len__() method definition.

As we have already said, this method should return an integer value. The following example raises an error because the __len__() method returns  a non-integer value.

class Example:
    def __len__(self):
        #returns a float
        return 5.0
e = Example()

#Calling the method directly works
print(e.__len__())

#raises an error
print(len(e))

One feature of the builtin len() function is that it takes only one argument, which is the object whose length we want. This also technically means that we are only supposed to have one required parameter in the __len__()'s definition, this parameter is the compulsory self. Defining more than one required parameters will result in an error if the len() function is called on the object.

class CustomList():
    def __init__(self, elements=[]): 
        self.elements = elements
     
    #The following method will rlead to an error if len() function is called.
    def __len__(self, b):
        return len(self.elements)

test_list = CustomList(elements=[1, 2, 3, 4, 5])

#Calling the method directly works
print(test_list.__len__("blahblah"))

#Calling len() function leads to an error
print(len(test_list))

Conclusion

  • The __len__() method returns the number of items in an object.
  • The len() function literally calls the __len__() method when called with an object
  • The __len__() method should strictly return an integer value for the len() function to work.
  • The __len__() method should not define required parameters apart from the compulsory, self.