Python __len__ Method Tutorial

  • Post author:
  • Post category:Python

In this section, we will learn what the __len__ method is and how to use it in Python.

What is __len__ Method in Python?

There is a function called `len()` that is used to return the number of elements in an iterable object. For example, if you call this function and pass a list object to it, it will return the number of elements that currently exist in that list.

So as long as the object is iterable (implemented the iterable protocol), this function knows how to get the length of elements in that object.

But what if we have a custom made object then? If we pass such an object to this function (as its argument), we will get an error, because the function does not know how to get elements of this object! Or even don’t know what are the elements to count?

But Python provided a method called `__len__` and if we override this method in our class, the `len()` function will call this method automatically and use the return value of the method as the return value of the `len()` function.

Python __len__ Method Syntax

def __len__(self):

Python __len__ Method Parameters

The method takes one argument, and that is a reference to the object that is passed as the argument of the len() function. Or basically the object that invoked the __len__ method.

Note that this argument will be passed automatically by the Python execution engine.

Python __len__ Method Return Value

The return value of the `__len__` method could be any value that is of type integer.

Example: using python __len__ method

class Employee: 
    
    def __init__(self, age, salary):
        self.age = age
        self.salary = salary

    def __len__(self):
        return self.salary 


jack = Employee(40, 300000)
john = Employee(60, 250000)

print(len(jack))
print(len(john))

Output:

300000

250000

For this example, we’ve decided to return the value of the `salary` attribute as the final value of the `__len__` method. This means now if we call the `len()` function and pass an object of type `Employee` as the argument of this function, the value of the `salary` attribute will return instead.

Note that the return value of the `__len__` method should be of type integer. Otherwise we will get an error.

Leave a Reply