Fix Python – Difference between len() and .__len__()?

Question

Asked By – Mark

Is there any difference between calling len([1,2,3]) or [1,2,3].__len__()?

If there is no visible difference, what is done differently behind the scenes?

Now we will see solution for issue: Difference between len() and .__len__()?


Answer

len is a function to get the length of a collection. It works by calling an object’s __len__ method. __something__ attributes are special and usually more than meets the eye, and generally should not be called directly.

It was decided at some point long ago getting the length of something should be a function and not a method code, reasoning that len(a)‘s meaning would be clear to beginners but a.len() would not be as clear. When Python started __len__ didn’t even exist and len was a special thing that worked with a few types of objects. Whether or not the situation this leaves us makes total sense, it’s here to stay.

This question is answered By – Mike Graham

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