Wednesday, June 18, 2025

Why is `len()` not a method in Python?

All Questions From This Chapter

Why does Python use len(collection) instead of collection.len()?

Great question! Python uses len(collection) instead of collection.len() primarily due to its design philosophy. Here's why:


🔹 1. Simplicity and Consistency (The Zen of Python)

Python follows the principle:

"There should be one– and preferably only one –obvious way to do it."

Having a standard function like len() that works across all built-in types (lists, strings, dicts, etc.) provides consistency.

python
len("hello") # 5 len([1, 2, 3]) # 3 len({'a': 1}) # 1

You don’t have to remember if it’s .size(), .length(), .count(), etc.


🔹 2. Uniform Interface for Built-ins and Custom Objects

len() is a built-in function that internally calls the special method __len__() on the object. This gives flexibility to customize behavior:

python
class MyList: def __len__(self): return 42 obj = MyList() print(len(obj)) # 42

If Python had used collection.len(), you'd need every class to implement that specific method name, and it wouldn’t be as universal.


🔹 3. Separation of Interface and Implementation

Using len(obj) separates the public interface (len) from the internal mechanics (__len__). This is more in line with Python’s philosophy of:

“We’re all consenting adults here.”


🔹 4. Easier to Use in Polymorphic Code

Since len() works with any object implementing __len__(), it allows for duck typing:

python
def print_length(x): print(len(x)) # Works for any x that defines __len__()

✅ Summary

Why len(x) is better than x.len()
More readable and consistent
Works across built-ins and user-defined types
Enables polymorphism via __len__()
Avoids inconsistent method names

So while x.len() might seem more "object-oriented," len(x) is more Pythonic.

Tags: Python,Interview Preparation,Technology,

No comments:

Post a Comment