Mark F Mark F - 1 year ago 86
Python Question

difference between len() and .__len__()?

Is there any difference between calling

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download