Many questions about cost of len(...)
are answered but I haven't found any link to Python documentation.
Is it by standard (documented in some PEP) or just way how it's currently implemented in most Python implementations?
Many questions about cost of len(...)
are answered but I haven't found any link to Python documentation.
Is it by standard (documented in some PEP) or just way how it's currently implemented in most Python implementations?
Documentation about time complexity for certain built-in python objects is here.
The len()
function in python just calls the __len__
method in your class. So if you built a custom class
class SlowLenList(object):
def __init__(self, mylist):
self.mylist = mylist
def __len__(self):
total = 1
for item in self.mylist:
total += 1
return total
Then the complexity would be O(n) in this case. So it really depends on the object you are calling. I assume the built-in list and other objects are O(1) because they have an attribute on an instance that increments every time an item is added to the object.