You can get the length of a large number of items. Lists, voice recorders, sets, other collections. So builtin len() , which calls type(obj).__len__(obj) internally, gives you the standard API to get the length.
If all of these collection types had a len() method that was called directly, there would be nothing to stop anyone from creating their own collection class that uses, for example. .length() or .length .
Here is an explanation from Guido van Rossum, the creator of Python:
First of all, I chose len(x) for x.len() for HCI reasons ( def __len__() came much later). There are actually two related reasons: and HCI:
(a) For some operations, prefix notation is better read than postfix - prefix (and infix!) operations have a long tradition in mathematics, which loves notes in which the mathematician thinks about a problem. Compare the ease with which we rewrite a formula like x*(a+b) in x*a + x*b for awkwardness by doing the same thing using raw OO notation.
(b) When I read the code that says len(x) , I know that it asks for the length of something. This tells me two things: the result is integer, and the argument is some kind of container. Otherwise, when I read x.len() , I should already know that x is a kind of container that implements an interface or inherits from a class that has the standard len() . Witness the confusion we sometimes have when a class that does not implement a mapping has a get() or keys() method or something that is not a file has a write() method.
Saying the same thing differently, I see "len" as an inline operation. I would love to lose this. I canβt say for sure whether you mean it or not, but βdef len (self): ...β seems like you want to downgrade it to the usual method. I'm very -1 on this.
source share