There are multiple distinct questions on the following topic, so we need multiple canonicals. How can we come up with canonicals?
A longstanding source of Python new-user confusion, even predating SO by a decade, is why len()
is a function not a method, when to use len() vs __len__(), what this means for OOP, inheritance and various related things. There is a lot of confusion, duplication and poorly-worded non-generic questions which happened to attract the best answers over the years.
Following are various askings, some of which are suitable for canonicals, and some of which aren't. Please also mention other useful ones.
- Why does Python code use len() function on strings instead of a string length method?
- renamed from "Is there a reason Python strings don't have a string length method?"
- a good question even though it boils down to "Why does Python code generally call
len()
instead of a method such as__len__
?" - the OP asked about strings, but the question and answers apply to all builtins
- Why isn't the 'len' function inherited by dictionaries and lists in Python
- boils down to the same question as above, but for all builtin types, although the wording is also not ideal as a dupe target
- Why does python use 'magic methods'?
- the user is not really asking about operators in general, but "why objects don't simply define a
len(self)
method and have it called directly as a member of the object, e.g.obj.len()
"
- the user is not really asking about operators in general, but "why objects don't simply define a
- In Python, when should I use a function instead of a method?
- the
len/__len__
dichotomy causes confusion on when we should use strict OO
- the
- Is arr.__len__() the preferred way to get the length of an array in Python?
- difference between len() and .__len__()?
- How to get the number of elements in a list in Python? - use
len()
- Cost of len() function on Python builtins is O(1) on almost all builtins
- Why Python function len is faster than __len__ method?
- a counterintuitive result, in CPython on builtin types
- Using len() and def __len__(self): to build a class
- how not to implement __len__ when writing your own class
- Making len() work with instance methods
- kind of a strange question, asking can you define different len() methods on different instances of a class, without modifying the class. Can't see why you would ever do this, other than for testing.
and two related near-identical questions, but with different terminology which is resistant to search:
len()
good,__len__()
bad" canonical answer just to avoid confusion for Python learners.__len__
to be a instance of some kind of "has-size" type class, where providing a specialized implementation of__len__
is the means by which you conform to that type class). A better question is why isn't there a__map__
?