How to Implement len Method in Python: Simple Guide
To implement the
len method in Python for your own class, define the special method __len__(self) that returns an integer representing the length. This allows you to use the built-in len() function on instances of your class.Syntax
To enable the len() function on your custom class, define the __len__ method inside it. This method must return an integer representing the length.
def __len__(self):— method signature- Return an integer value indicating the length or size
python
class MyCollection: def __len__(self): # return the length as an integer return 0
Example
This example shows a simple class that stores items in a list and implements __len__ to return the number of items. Using len() on an instance calls this method.
python
class Bag: def __init__(self): self.items = [] def add(self, item): self.items.append(item) def __len__(self): return len(self.items) bag = Bag() bag.add('apple') bag.add('banana') print(len(bag))
Output
2
Common Pitfalls
Common mistakes when implementing __len__ include:
- Not returning an integer (e.g., returning
Noneor a string) - Forgetting to define
__len__solen()raises an error - Returning negative numbers or floats, which are invalid
Always ensure __len__ returns a non-negative integer.
python
class WrongLen: def __len__(self): return 'five' # Wrong: should return int class CorrectLen: def __len__(self): return 5 # Correct obj_wrong = WrongLen() obj_correct = CorrectLen() # print(len(obj_wrong)) # This will raise a TypeError print(len(obj_correct)) # Outputs: 5
Output
5
Quick Reference
Summary tips for implementing __len__:
- Define
__len__(self)in your class - Return a non-negative integer
- Use
len()on your object to get this value - Raise no exceptions inside
__len__for smooth usage
Key Takeaways
Implement the __len__(self) method to enable len() on your class.
__len__ must return a non-negative integer representing length.
Using len(your_object) calls your __len__ method automatically.
Avoid returning non-integers or negative values in __len__.
Defining __len__ improves your class's compatibility with Python features.