typedef struct { PyObject_VAR_HEAD /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */ PyObject **ob_item; /* ob_item contains space for 'allocated' elements. The number * currently in use is ob_size. * Invariants: * 0 <= ob_size <= allocated * len(list) == ob_size * ob_item == NULL implies ob_size == allocated == 0 * list.sort() temporarily sets allocated to -1 to detect mutations. * * Items must normally not be NULL, except during construction when * the list is not yet visible outside the function that builds it. */ Py_ssize_t allocated; } PyListObject;
list 本質上是一個長度可變的連續陣列。其中 ob_item 是一個指標列表,裡邊的每一個指標都指向列表中的元素,而 allocated 則用於儲存該列表目前已被分配的空間大小。有興趣的讀者,可直接閱讀 list 列表實現的原始碼檔案 listobject.h 和 listobject.c。
allocated >= len(list) = ob_size >= 0
。typedef struct { PyObject_VAR_HEAD PyObject *ob_item[1]; /* ob_item contains space for 'ob_size' elements. * Items must normally not be NULL, except during construction when * the tuple is not yet visible outside the function that builds it. */ } PyTupleObject;
tuple 和 list 相似,本質也是一個陣列,但是空間大小固定。不同於一般陣列,Python 的 tuple 做了許多優化,來提昇在程式中的效率。有興趣的讀者,可閱讀 tuple 元組實現的原始碼檔案 tupleobject.h 和 tupleobject.c。
static PyTupleObject *free_list[PyTuple_MAXSAVESIZE];
所有申請過的,小於一定大小的元組,在釋放的時候會被放進這個 free_list 中以供下次使用。也就是說,如果以後需要再去建立同樣的 tuple,Python 就可以直接從快取中載入。