Syntax
object.__len__(self)
💡 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()
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__()
class Data: def __len__(self): return 42 a = Data() print(len(a)) # 42 print(bool(a)) # True --> Because 42 != 0
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.
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.