Difference between len() and .__len__()?

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.

Leave a Comment