Time complexity of tuple in Python

て烟熏妆下的殇ゞ 提交于 2019-12-07 03:33:38

问题


There is similar question about hash (dictionaries) and lists, also there is a good piece of info here: http://wiki.python.org/moin/TimeComplexity

But I didn't find anything about tuples.

The access time for

data_structure[i]
  • for a linked list is in general O(n)
  • for dictionary is ~ O(1)

What about tuple? Is it O(n) like for a linked list or O(1) like for an array?


回答1:


It's O(1) for both list and tuple. They are both morally equivalent to an integer indexed array.




回答2:


Lists and tuples are indexable in the exact same way arrays are in other languages.

A simplified explanation is that space is allocated for references to objects, those references take up a uniform amount of space, and any index is simply multiplied by the size of the reference to get an offset into the array. This gives constant, O(1), access for lists and tuples.




回答3:


Getting an item from a linked-list is O(n), but Python lists have array-based implementations so the cost is O(1).

Tuples are also implemented using arrays so it's O(1) for them too.




回答4:


It should be O(1), because it really is only a list.

But for python lists, I'd expect O(1) too! You might want to think about it again...



来源:https://stackoverflow.com/questions/6153348/time-complexity-of-tuple-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!