Python列表的底层结构:数组为何能存储不同类型对象?
Great question—this is such a common point of confusion when you start digging into Python's internals, and your core understanding of arrays is totally correct! Traditional arrays (like the ones you’d use in C or Java) do require all elements to be the same primitive type. But Python’s list uses a clever twist on this idea.
Here’s the breakdown:
- The underlying structure of a Python list is an array, but it’s not an array of the actual objects you store. Instead, it’s an array of pointers (references) to Python objects.
- Every Python object—whether it’s an integer, string, boolean, or custom class instance—fits into a common base structure (think of it as a
PyObject*in CPython’s C implementation). All these pointers are the same size (e.g., 8 bytes on a 64-bit system), so the underlying array can be a homogeneous array of these pointer values.
For example, when you create a list like:
my_list = [42, "hello world", False]
The underlying array doesn’t store the integer 42, the string characters, or the boolean value directly. Instead, it stores three pointers: one pointing to the integer object 42, another pointing to the string object "hello world", and a third pointing to the boolean object False. Since all pointers are the same type/size, the array stays true to the "homogeneous type" rule, while the objects they point to can be totally different.
This design gives Python lists their flexibility (you can mix and match types freely) while retaining the efficiency of an array—like O(1) access time by index, since the underlying array lets us jump directly to the pointer we need.
内容的提问来源于stack exchange,提问作者Goktug

