一尘不染

Python-删除,删除和弹出列表之间的区别

python

`>>> a=[1,2,3]

a.remove(2)
a
[1, 3]
a=[1,2,3]
del a[1]
a
[1, 3]
a= [1,2,3]
a.pop(1)
2
a
[1, 3]
`

以上三种从列表中删除元素的方法之间有什么区别吗?


阅读 346

收藏
2020-02-15

共1个答案

一尘不染

是的,remove删除第一个匹配值,而不是特定的索引:

>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]

del 删除特定索引处的项目:

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

并pop从特定索引处删除该项目并返回。

>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]

它们的错误模式也不同:

>>> a = [4, 5, 6]
>>> a.remove(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> del a[7]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> a.pop(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range
2020-02-15