Fix Python – Why does Python code use len() function instead of a length method?

Question

Asked By – fuentesjr

I know that python has a len() function that is used to determine the size of a string, but I was wondering why it’s not a method of the string object.

Update

Ok, I realized I was embarrassingly mistaken. __len__() is actually a method of a string object. It just seems weird to see object oriented code in Python using the len function on string objects. Furthermore, it’s also weird to see __len__ as the name instead of just len.

Now we will see solution for issue: Why does Python code use len() function instead of a length method?


Answer

Strings do have a length method: __len__()

The protocol in Python is to implement this method on objects which have a length and use the built-in len() function, which calls it for you, similar to the way you would implement __iter__() and use the built-in iter() function (or have the method called behind the scenes for you) on objects which are iterable.

See Emulating container types for more information.

Here’s a good read on the subject of protocols in Python: Python and the Principle of Least Astonishment

This question is answered By – Jonny Buchanan

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0