Python __len__() Magic Method

5/5 - (2 votes)

Syntax

object.__len__(self)

The Python __len__ method returns a positive integer that represents the length of the object on which it is called. It implements the built-in len() function. For example, if you call len(x) an object x, Python internally calls x.__len__() to determine the length of object x.

We call this a “Dunder Method” for Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

💡 Useful Knowledge: If the __bool__() dunder method is not defined, Python internally returns __len__() != 0 to determine whether the object’s associated Boolean value is True or False.

Background len()

Python’s built-in function len() returns the length of the given string, array, list, tuple, dictionary, or any other iterable.

The type of the return value is an integer that represents the number of elements in this iterable.

Python len() – A Simple Guide

Before we learn more about the __len__() dunder method, let’s have a look at a couple of basic len() examples:

>>> friends = ['Alice', 'Bob', 'Carl', 'Ann']
>>> len(friends)
4
>>> friends.extend([1, 2, 3])
>>> len(friends)
7
>>> len('hello world')
11
>>> len('hi')
2
>>> len((1, 2, 3))
3
>>> len({42, 21})
2
>>> age = {'Alice': 18, 'Bob': 21}
>>> len(age)
2
>>> age['Carl'] = 33
>>> len(age)
3

Example Custom __len__()

In the following example, you create a custom class Data and overwrite the __len__() method so that it returns a dummy number.

class Data:
    def __len__(self):
        return 42


a = Data()

print(len(a))
# 42

print(bool(a))
# True    --> Because 42 != 0

If you hadn’t defined the __len__() method, Python would’ve raised an error:

Default __len__() Implementation

If you call len(x) on an object on which the x.__len__() dunder method is not defined, Python will raise a TypeError: object of type '...' has no len(). To fix this error, simply define the __len__() method in the class definition before calling len() on an object.

class Data:
    pass


a = Data()
print(len(a))

Here’s the error message:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 7, in <module>
    print(len(a))
TypeError: object of type 'Data' has no len()

What’s the Difference Between len(x) and x.__len__()?

The result of len(x) and x.__len__() is the same: both return the number of elements in the object, i.e., more generally, its length.

Have a look at this example:

>>> len([1, 2, 3])
3
>>> [1, 2, 3].__len__()
3

The difference between len(x) and x.__len__() is only syntactical sugar. The former built-in function calls the latter method internally to implement the correct behavior. So, there’s no semantic difference between both ways to obtain the length of an object.

References:

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!