Might be a weird question. But I have been scratching my head over why if you want to get the length of a list you can’t simply say list.len() and you have to pass the list to len() to get its size? And where this len() is actually coming from?
Share
You can get the length of a lot of items. Lists, dicts, sets, other collections. So the builtin
len()that callstype(obj).__len__(obj)internally gives you a standard API to get the length.If all those collection types had a
len()method that was called directly there would be nothing to prevent someone from creating a custom collection class that uses e.g..length()or a.lengthproperty.Here’s the explanation from Guido van Rossum, the creator of Python: