Python often USES list data structure summaries
- 2020-04-02 13:55:50
- OfStack
This article summarizes the Python list of some commonly used object methods for beginners to refer to or query, as follows:
1. List. Append (x)
Adding element x to the end of the list is 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. The list. The extend (L)
To add all the elements in one list to another, 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)
Insert the element x before the 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),10)
>>> a
[-3, 1, 2, 3, 4, 5, -2, 5, 9, 7, 10]
4. List. Remove (x)
Delete the element x (which appears for the first time), The code is as follows:
>>> a
[-3, 1, 2, 3, 4, 5, -2, 5, 9, 7, 10]
>>> a.append(1)
>>> a
[-3, 1, 2, 3, 4, 5, -2, 5, 9, 7, 10, 1]
>>> a.remove(1)
>>> a
[-3, 2, 3, 4, 5, -2, 5, 9, 7, 10, 1]
5. List. The count (x)
Calculate the number of occurrences of element x
, the code is as follows:
>>> a
[-3, 2, 3, 4, 5, -2, 5, 9, 7, 10, 1]
>>> a.count(3)
1
6. List. Sort ()
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 ()
Invert the elements in the list
, the code is as follows:
>>> a
[-3, -2, 1, 2, 3, 4, 5, 5, 7, 9, 10]
>>> a.reverse()
>>> a
[10, 9, 7, 5, 5, 4, 3, 2, 1, -2, -3]
8. The list. The index (x)
Returns the first index in the table whose value appears to be x
, the code is as follows:
>>> a
[10, 9, 7, 5, 5, 4, 3, 2, 1, -2, -3]
>>> a.index(9)
1
Pop (I) is 9. The list.
Deletes an element from the specified position I in the list and returns it, or, if no position is specified, deletes the last element in the list and returns it
. The code is as follows:
>>> a
[10, 9, 7, 5, 5, 4, 3, 2, 1, -2, -3]
>>> a.pop(0)
10
>>> a
[9, 7, 5, 5, 4, 3, 2, 1, -2, -3]
>>> a.pop()
-3