Python list Implementation and Pythonlist implementation
Original article link
This article introduces how list is implemented in Python.
List is particularly useful in Python. Let's take a look at how the list is implemented internally.
Let's look at the simple program below, add some integers in the list and print them out.
>>> L = []>>> L.append(1)>>> L.append(2)>>> L.append(3)>>> L[1, 2, 3]>>> for e in L:... print e... 1 2 3
As you can see, list can be iterated.
C structure of List object
In Python, list is represented by the structure of the C language below.ob_itemIs an array of pointers used to save elements, and allocated isob_itemTotal pre-allocated memory capacity
typedef struct { PyObject_VAR_HEAD PyObject **ob_item; Py_ssize_t allocated;} PyListObject;
List Initialization
Let's take a look at what happened when initializing an empty list. L = []
arguments: size of the list = 0returns: list object = []PyListNew: nbytes = size * size of global Python object = 0 allocate new list object allocate list of pointers (ob_item) of size nbytes = 0 clear ob_item set list's allocated var to 0 = 0 slots return list object
It is very important to know the size of the memory space requested by the list (which is replaced by allocated later) and the size of the space occupied by the actual storage elements of the list (ob_size,ob_sizeAndlen(L)The size of allocated is the size of the applied space in the memory. Generally, you will see that the value of allocated is equalob_sizeThe value must be large. This is to avoid calling realloc for memory allocation every time a new element is added to the list. Next we will see