Common methods of Python list and its underlying implementation

Add element

append()
Method is used to append an element to the end of the list

list_test = ['2','a','b']
#Append element
list_test.append(1)
print(list_test)

#The entire element is treated as an element
list_test.append(('e',))
print(list_test)

result
['2', 'a', 'b', 1]
['2', 'a', 'b', 1, ('e',)]

When passing a list or tuple to the append() method, the method will treat them as a whole and add them to the list as an element, forming a new list containing the list and tuple.

extend()
The difference between extend() and append() is that extend() does not treat the list or ancestor as a whole, but adds the elements contained in them to the list one by one.

list_test = ['2','a','b']
#Append element
list_test.extend('1')
print(list_test)

#The entire element is treated as an element
list_test.extend(('e',))
print(list_test)

result
['2', 'a', 'b', '1']
['2', 'a', 'b', '1', 'e']

It should be noted here that extend is equivalent to an iterator adding data to the specified list one by one

insert()
The append() and extend() methods can only insert elements at the end of the list. If you want to insert elements in the middle of the list, you can use the insert() method.

list_test = ['2','a','b']
#Append element
list_test.insert(0,'1')
print(list_test)

list_test.insert(1,('e',))
print(list_test)

result
['1', '2', 'a', 'b']
['1', ('e',), '2', 'a', 'b']

Delete element

del

del is a keyword in Python, which is specially used to perform deletion. It can not only delete the whole list, but also delete some elements in the list

list_test = ['2','a','b']
#According to index
del list_test[0]
print(list_test)

#Delete a continuous paragraph
del list_test[::-1]
print(list_test)

result
['a', 'b']
[]

pop()
Delete element based on index value

list_test = ['2','a','b']
list_test.pop(0)
print(list_test)

#No index specified
list_test.pop()
print(list_test)

result
['a', 'b']
[]

remove()
Delete according to element value
In addition to the del keyword, Python also provides a remove() method, which will delete according to the value of the element itself.

It should be noted that the remove() method will only delete the first element with the same value as the specified value, and the element must be guaranteed to exist, otherwise a ValueError error will be raised.

list_test = ['2','a','b']
list_test.remove('a')
print(list_test)

#No index specified
list_test.remove('c')
print(list_test)

result
['2', 'b']
ValueError: list.remove(x): x not in list

clear()
Delete all elements of the list
Python clear() is used to delete all elements of the list, that is, to empty the list

list_test = ['2','a','b']
list_test.clear()
print(list_test)

result
[]

Modify element

Modify a single element and directly assign a value to the element

Modify a single element

list_test = ['2','a','b']
list_test[0]='1'
print(list_test)

result
['1', 'a', 'b']

Modify a set of elements
Python supports assigning values to a set of elements through slicing syntax. In this operation, if the step size is not specified, python does not require the number of newly assigned elements to be the same as the number of original elements; This means that the operation can add or delete elements for the list.

list_test = ['2','a','b','v']
list_test[0:2]=['c','d','e']
print(list_test)

result
['c', 'd', 'e', 'b', 'v']

Find element

**index() **
The index() method returns the index value in the list where the element is located.
The index() method is used to find the position of an element in the list (that is, the index). If the element does not exist, it will lead to ValueError error. Therefore, it is best to use the count() method to judge before finding.

list_test = ['2','a','b']
print(list_test.index('a'))
print(list_test.index('a',0,2))

result
1
1

count()
The count() method is used to count the number of times an element appears in the list

list_test = ['2','a','b']
print(list_test.count('a'))

result
1

A brief description of the underlying implementation of the list

The specific structure is as follows

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;

A list is essentially a continuous array with variable length. Where ob_item is a pointer list, in which each pointer points to the elements in the list, and allocated is used to store the size of the allocated space in the list

It should be noted that the actual space size of allocated is different from that of the list. The actual space size of the list refers to the result returned by len(list), that is, OB annotated in the above code_ Size, indicating the total number of elements stored in the list. In practice, in order to optimize the storage structure and avoid reallocating memory every time an element is added, the allocated space in the list is often greater than ob_size

Therefore, allocated and ob_ The relationship of size is: allocated > = len (list) = ob_size >= 0.

If the allocated space of the current list is full (i.e. allocated == len(list)), it will request the system for more memory space and copy all the original elements.

Keywords: Python

Added by magaly on Tue, 07 Dec 2021 15:18:40 +0200