Python list Implementation and Pythonlist implementation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.