Learn python list collection

phtyon list sequence specific

  • Similar to the array of high-level languages ​​such as java, the difference is that it can put any type of element

List creation

grammar

>>> a = [10,20,'hello world',True]
>>> a = [] # 创建一个空字符串

Use list() to create any iterable element as a list

>>> a = list()
>>> a
[]
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = list('hello world')
>>> a
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

range() function

The range() function can easily help us create a list of integers

grammar

range(start,end,step)
parameter meaning
start Optional, indicating the starting value
end Required, marking the end value (the result does not include the end value)
step Step size, default is 1, -1 indicates to pick backward

Case

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(0,20,2))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> list(range(20,0,-1))
## 表示从20到0,逆顺序截取
[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> 

Add element

append method

>>> a = [1,2,3]
>>> a.append(4)
>>> a
[1, 2, 3, 4]
>>> 

+ Operator method to add elements

Note : It is not really adding elements to the tail, but creating a new list of objects; it consumes more memory and is time-consuming

>>> a = [1,2,3]
>>> a = a+[4,5,6]
>>> a
[1, 2, 3, 4, 5, 6]
>>> 

extend() method

Add all elements of the target list to the end of this list, do not create new objects, it is recommended

>>> a = [12,3,4]
>>> a.extend([5,6,7])
>>> a
[12, 3, 4, 5, 6, 7]
>>> 

insert() method

The insert method can insert elements at any position in the list, but it also means that the elements will be moved, which will affect the processing speed

>>> a = [2,4,5,7]
>>> a.insert(2,9)
>>> a
[2, 4, 9, 5, 7]
>>> 

Delete element

Use del keyword

The principle of copying objects used at the bottom layer is expensive, similar to the insert method

>>> a = [1,2,3,4]
>>> del a[1]
>>> a
[1, 3, 4]
>>> 

Use pop() function

The pop function can delete the function at the specified position, if not provided, the last element will be deleted by default

>>> a = [1,2,3,4,7]
>>> a.pop()
7
>>> a
[1, 2, 3, 4]
>>> a.pop(0)
1
>>> a
[2, 3, 4]
>>> 

remove() function

Delete the specified element that appears for the first time, and report an exception if it does not exist

>>> a = [1,2,3,4,5,7]
>>> a.remove(2)
>>> a
[1, 3, 4, 5, 7]
>>> a.remove(6)
Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    a.remove(6)
ValueError: list.remove(x): x not in list
>>> 

Guess you like

Origin blog.csdn.net/qq_42418169/article/details/108985586