How come list element lookup is O(1) in Python?

前端 未结 3 1825
盖世英雄少女心
盖世英雄少女心 2021-02-03 21:36

Today in class, we learned that retrieving an element from a list is O(1) in Python. Why is this the case? Suppose I have a list of four items, for example:

3条回答
  •  死守一世寂寞
    2021-02-03 22:23

    When you say a = [...], a is effectively a pointer to a PyObject containing an array of pointers to PyObjects.

    When you ask for a[2], the interpreter first follows the pointer to the list's PyObject, then adds 2 to the address of the array inside it, then returns that pointer. The same happens if you ask for a[0] or a[9999].

    Basically, all Python objects are accessed by reference instead of by value, even integer literals like 2. There are just some tricks in the pointer system to keep this all efficient. And pointers have a known size, so they can be stored conveniently in C-style arrays.

提交回复
热议问题