4 ms·
Well, there are two parts here: First, why does Python have a method instead of an attribute, and second, why is it external instead of internal to the object?
by MostAwesomeDude 14y ago
Well, there are two parts here: First, why does Python have a method instead of an attribute, and second, why is it external instead of internal to the object?
To answer the first question, Python allows you to ask about the size of any finite collection, including collections for which knowing the actual length could require an O(n) (or greater!) traversal, and collections which are mutable and can have lengths which change. A method is a far better fit than an attribute for describing the length, since it is something that might have to be calculated rather than being known a priori.
(Of course, nearly all collections keep accounting of their length at all times, but the reasoning is still there.)
The second reason, about len() being external to collections, is related to Python's heritage. I posit, without proof, that len() is external because Python's granddaddy is Smalltalk, where iteration and collection manipulation are external, inverted from what we would expect in other modern languages.
Now, with all of this said, the actual reasons are lost to history, and I don't know if anybody actually knows the exact reason for the design decision anymore. But, nonetheless, that's the way that it is. Hope this was interesting.
Edit: Well, never mind, looks like Guido did explain it. Today I learned things. Leaving this up for posterity, but please do ignore it.