NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior1 view

Why is a contiguous block of memory allocated for a list in Python?

Practice

Asked at

AI answer

In CPython, list is implemented as a dynamic array: pointers to objects are stored in a contiguous region of memory, while the objects themselves can be located in different places in memory. This provides O(1) index access and good data locality. When elements are added, the list sometimes allocates a larger array and copies the pointers; spare capacity allows append to run in amortized O(1) time. Therefore, inserting into or deleting from the middle usually requires shifting pointers and takes O(n). The implementation details of other Python implementations may differ.