Time complexity of tuple in Python

萝らか妹 提交于 2019-12-05 07:10:01

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

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.

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.

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...

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