Why is a list access O(1) in Python?

前端 未结 4 807
余生分开走
余生分开走 2021-02-08 16:05

I understand that a list is different from an array. But still, O(1)? That would mean accessing an element in a list would be as fast as accessing an element in a dict, which we

4条回答
  •  一整个雨季
    2021-02-08 16:26

    Get item is getting an item in a specific index, while lookup means searching if some element exists in the list. To do so, unless the list is sorted, you will need to iterate all elements, and have O(n) Get Item operations, which leads to O(n) lookup.

    A dictionary is maintaining a smart data structure (hash table) under the hood, so you will not need to query O(n) times to find if the element exists, but a constant number of times (average case), leading to O(1) lookup.

提交回复
热议问题