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.
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:
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:
✅ 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.
No comments:
Post a Comment