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

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

    accessing a list l at index n l[n] is O(1) because it is not implemented as a Vanilla linked list where one needs to jump between pointers (value, next-->) n times to reach cell index n.

    If the memory is continuous and the entry size would had been fixed, reaching a specific entry would be trivial as we know to jump n times an entry size (like classic arrays in C).

    However, since list is variable in entries size, the python implementation uses a continuous memory list just for the pointers to the values. This makes indexing a list (l[n]) an operation whose cost is independent of the size of the list or the value of the index.

    For more information see http://effbot.org/pyfaq/how-are-lists-implemented.htm

提交回复
热议问题