假设我们有一个列表 a=[1,2,3,4,1,2,4,5]
指定元素进行删除
remove(x)
remove() 函数用于移除列表中 某个值的第一个匹配项,如果有多个则删除第一个 ,
注意list中不存在x,执行会报错
无法指定位置进行删除
>>> a=[1,2,3,4,1,2,4,5]
>>> a.remove(1)
>>> a
[2, 3, 4, 1, 2, 4, 5]
>>> a.remove(7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
指定位置进行删除
pop(index)
删除index位置上的元素,并返回该位置上的元素值
如果index越界则会报错
>>> a=[1,2,3,4,1,2,4,5]
>>> a.pop(-1)
5
>>> a
[1, 2, 3, 4, 1, 2, 4]
>>> a.pop(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range
del x[index]
和pop所实现的功能是一样的,但是这个没有返回的值
>>> a=[1,2,3,4,1,2,4,5]
>>> del a[-1]
>>> a
[1, 2, 3, 4, 1, 2, 4]
>>> del a[-10]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>>