Subtitle: How to Use __len__ in a Class to Make len() Work
Introduction
Python is a beautifully flexible language that allows you to design your own classes that mimic the behavior of built-in types. One such use case is when you create a custom class, say CustomList, and you want it to behave like a native list. But if you try to use len(custom_list) on your object and it throws an error or doesn’t return the expected result, it means your class isn’t fully ready. So, how do you fix this? The answer lies in Python’s special methods — particularly the __len__() method.

How __len__() Works
In Python, when you call len(object), it internally calls the object’s __len__() method. If that method is not defined, Python doesn’t know how to compute the length, and it raises a TypeError.
The Problem:
class CustomList:
def __init__(self, items):
self.items = items
custom_list = CustomList([1, 2, 3])
print(len(custom_list)) # TypeError: object of type 'CustomList' has no len()
This error occurs because Python doesn’t know what len(custom_list) means unless you explicitly define how to compute the length of your CustomList object.

The Solution: Define __len__()
To make len(custom_list) work, add a __len__() method in your class like this:
pythonCopyEditclass CustomList:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
custom_list = CustomList([1, 2, 3])
print(len(custom_list)) # Output: 3
Now your custom object responds to len() just like a native list. Python internally calls custom_list.__len__() and gets the right result.

Conclusion
If you want your custom Python class to behave like a built-in list, especially when using the len() function, you must define the special method __len__(). It allows Python to treat your class instance like a list, making your code more intuitive, readable, and Pythonic. Whether you’re building custom data structures or enhancing objects for more functionality, understanding and using special methods like __len__() brings your classes to life — just like the built-in types we use every day.