3

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?

George Sovetov
  • 4,942
  • 5
  • 36
  • 57
  • 1
    Clearly `O(1)` for lists: https://wiki.python.org/moin/TimeComplexity – Moses Koledoye Jul 24 '16 at 15:18
  • There's a thread with something similar here, but Alex Martelli did not provide any doc refs: [Cost of len() function](http://stackoverflow.com/questions/1115313/cost-of-len-function) – Moses Koledoye Jul 24 '16 at 15:22
  • @MosesKoledoye This question raised exactly after I read question you mention. Thanks for link, it really answers at least part of question. – George Sovetov Jul 24 '16 at 15:25

1 Answers1

2

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.

erip
  • 16,374
  • 11
  • 66
  • 121
General Kandalaft
  • 2,215
  • 2
  • 18
  • 25
  • Indeed, there are no guarantees on constant time `len` for custom classes. This answer should be here for the sake of completeness. But question is specifically about built-ins. – George Sovetov Jul 24 '16 at 16:06
  • Thanks @GeorgeSovetov I just wanted to give a brief explanation of how len() works so readers don't assume len() _always_ has the same time complexity (like it has some magic super efficient algorithm that works in all cases). – General Kandalaft Jul 24 '16 at 16:30
  • That's fine. As I said, this answer should be here. – George Sovetov Jul 24 '16 at 16:32