Wednesday, June 18, 2025

What is the purpose of __len__ in a Python class?

All Questions From This Chapter

__len__ in a Python class?

The purpose of __len__ in a Python class is to define how the built-in len() function should behave when called on an instance of that class.

Why it's used:

  • When you implement __len__, you're telling Python how to compute the "length" of your custom object.

Example:

python
class MyCollection: def __init__(self, items): self.items = items def __len__(self): return len(self.items) c = MyCollection([1, 2, 3]) print(len(c)) # Output: 3

Key Points:

  • __len__ must return an integer ≥ 0.

  • If __len__ is not defined, calling len() on the object will raise a TypeError.

It’s especially useful when creating custom container types that conceptually hold multiple items.

Tags: Python,Interview Preparation,Technology,

No comments:

Post a Comment