python中删除list元素的方法del()、pop()和remove()

时间:2022-12-09 23:12:50

del():根据下标进行删除

In [1]: a = [1, 2, 3, 4, 5]
In [2]: del a[0]
In [3]: a
Out[4]: [2, 3, 4, 5]

pop(): 删除最后一个元素

In [1]: a = [1, 2, 3, 4, 5]
In [2]: a.pop()
Out[2]: 5
In [3]: a
Out[3]: [1, 2, 3, 4]

remove(): 根据元素的值进行删除

In [1]: a = [1, 2, 3, 4, 5]
In [2]: a.remove(3)
In [3]: a
Out[3]: [1, 2, 4, 5]