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

2022-09-05 01:05:02

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

>>> 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]

答案 1

从列表中删除元素的三种不同方法的效果:

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

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

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

>>> a = [9, 8, 7, 6]
>>> del a[1]
>>> a
[9, 7, 6]

并删除特定索引处的项目并返回它。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

答案 2

用于按索引删除元素,如果需要返回值,则按索引删除元素,以及按值删除元素。最后一个需要搜索列表,如果列表中没有出现此类值,则引发。delpop()remove()ValueError

从元素列表中删除索引时,这些方法的计算复杂性为in

del     O(n - i)
pop     O(n - i)
remove  O(n)