Where can I find the time and space complexity of the built-in sequence types in Python

前端 未结 3 1875
走了就别回头了
走了就别回头了 2021-02-12 18:15

I\'ve been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could

3条回答
  •  悲&欢浪女
    2021-02-12 18:44

    Raymond D. Hettinger does an excellent talk (slides) about Python's built-in collections called 'Core Python Containers - Under the Hood'. The version I saw focussed mainly on set and dict, but list was covered too.

    There are also some photos of the pertinent slides from EuroPython in a blog.

    Here is a summary of my notes on list:

    • Stores items as an array of pointers. Subscript costs O(1) time. Append costs amortized O(1) time. Insert costs O(n) time.
    • Tries to avoid memcpy when growing by over-allocating. Many small lists will waste a lot of space, but large lists never waste more than about 12.5% to overallocation.
    • Some operations pre-size. Examples given were range(n), map(), list(), [None] * n, and slicing.
    • When shrinking, the array is realloced only when it is wasting 50% of space. pop is cheap.

提交回复
热议问题