Basic operation of Python list

1. Add an element to the last position in the list
list1 = [1,2,3,4]
list1.append (1)
list1 = [1,2,3,4,1]
list1 [2] = 3 read the list The third element in
list1 [-2] = 4 reads the penultimate element
2 in the list and adds the list to another list
list1.extend ([5,3,2])
list1 = [1,2, 3,4,1,5,3,2]
3. Insert an element at a specific position in the list
list1.insert (2,8)
list1 = [1,2,8,3,4,1,5,3,2 ]
4. Exchange the position of elements in the list
Use temporary variables temp
temp = list1 [1]
list1 = [1,2,8,3,4,1,5,3,2]
list1 [1] = list1 [2]
list1 = [1,8,8,3,4,1,5,3,2]
list1 [2] = temp
list1 = [1,8,2,3,4,1,5,3,2]
5. Delete One element
list1.remove (8)
list1 = [1,8,2,3,4,1,5,3]
del list1 [2]
list1 = [1,8,3,4,1,5,3]
6 , Take out the last element in the list
list1.pop () = 3
list1.pop (3) = 4
list1 = [1,8,3,1,5]
7, list slice slice
list2 = [1,3,2,4,6,7,4 , 21]
list2 [0: 3] = [1,3,2]
list2 [: 3] = [1,3,2]
list2 [4: 7] = [6,7,4]
list2 [4:] = [6,7,4]
list2 [:] = [1,3,2,4,6,7,4,21]
8. The operator acts on the list
> comparison operator
list1> list2 The result is False
+ splicing operator
list1 + list2 = [1,8,3,1,3,2,4,6,7,4,21]
* Repeat operator
list1 ※ 3 = [1,8,3,1,8,3,1, 8,3]
in / not in
1 in list1 results in True
2 not in list1 results in True
9, dir (list) Check list related built-in functions.
Count () count.
Index () index
list1.index (1,2, 5) = 3 The
second parameter is the start value of the index range, and the third parameter is the end value.
.reverst () reverse order
.sort () sorts from small to large by default, equivalent to .sort (reverst = false)
.sort (reverst = true) sorts from large to small
cmp (list1, list2): compares the elements of two lists
len (list1): list
Number of elements max (list1): return the maximum value of list elements
min (list1): return the minimum value of
list elements list (seq): convert tuples to lists

Published 38 original articles · Like 29 · Visits 10,000+

Guess you like

Origin blog.csdn.net/weixin_45270982/article/details/104175891