This article summarizes some common object methods in the Python list List for beginners to reference or query, as follows:
1.list.append (x)
add element x to the end of the list, equivalent to A[len (a):] =[x, the code is as follows:
>>> a=[1,2,3,4,5]
>>> a
[1, 2, 3, 4, 5]
>>> a.append ( -2)
>>> A
[1, 2, 3, 4, 5,-2]
2. List.extend (L)
Add all the elements from one list to another list, equivalent to A[len (a):] = L, the code is as follows:
>>> a
[1, 2, 3, 4, 5,-2]
>>> l=[5,9,7]
>>> L
[5, 9, 7]
>>> A.extend (L)
>>> a
[1, 2, 3, 4, 5,-2, 5, 9, 7]
3. List.insert (i,x)
before inserting element x into index number I , the code is as follows:
>>> a
[1, 2, 3, 4, 5,-2, 5, 9, 7]
>>> A.insert (0,-3)
>>> a
[-3, 1, 2, 3, 4, 5, -2, 5, 9, 7]
>>> A.insert (Len (a), ten)
>>> a
[-3, 1, 2, 3, 4, 5,-2, 5, 9, 7, 10]
4. List.remove (x)
Delete element x (first occurrence) with the following code:
>>> a
[ -3, 1, 2, 3, 4, 5,-2, 5, 9, 7, ten]
>>> a.append (1)
>>> a
[-3, 1, 2, 3, 4, 5,-2, 5, 9, 7, 1]
>>> a.remove (1)
>>> A [-3, 2, 3, 4, 5, 2, 5,
9, 7, 10, 1]
5. List.count (x)
calculates the number of times element x appears , as follows:
>>> a
[ -3, 2, 3, 4, 5,-2, 5, 9, 7, ten, 1]
>>> a.count (3)
1
6. List.sort ()
to sort the list elements , the code is as follows:
>>> a.sort ()
>>> a
[-3,-2, 1, 2, 3, 4, 5, 5, 7, 9, 10]
7. List.reverse ()
To rearrange the elements in a table , the code is as follows:
>>> a
[ -3,-2, 1, 2, 3, 4, 5, 5, 7, 9, ten]
>>> a.reverse ()
>>> a
[10, 9, 7, 5, 5, 4, 3, 2, 1,-2,-3]
8. List.index (x)
returns the first index in the table that appears with a value of x , as follows:
>>> a
[9, 7, 5, 5, 4, 3, 2, 1,-2,-3]
>>> a.index (9)
1
9. List.pop (i)
specify location from the list I deletes the element and returns it, and if not, deletes the last element of the list and returns the element. The code is as follows:
>>> a [9, 7, 5, 5, 4, 3, 2, 1,-2,-3] >>> a.pop (0) >>> A [9, 7, 5, 5, 4, 3, 2, 1,-2,-3] >>> A.pop ()-3