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

前端 未结 4 789
余生分开走
余生分开走 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:48

    That is because Python stores the address of each node of a list into a separate array. When we want an element at nth node, all we have to do is look up the nth element of the address array which gives us the address of nth node of the list by which we can get the value of that node in O(1) complexity.

    Python does some neat tricks to make these arrays expandable as the list grows. Thus we are getting the flexibility of lists and and the speed of arrays. The trade off here is that the compiler has to reallocate memory for the address array whenever the list grows to a certain extent.

    amit has explained in his answer to this question about why lookups in dictionaries are faster than in lists.

提交回复
热议问题