>>> 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
是,
remove
首先删除匹配值而不是特定索引:del
删除特定索引处的项:并且
pop
移除特定索引处的项并返回它。它们的错误模式也不同:
由于没有其他人提到它,请注意
del
(与pop
不同)允许由于列表切片而删除一系列索引:如果索引不在列表中,这还允许避免
IndexError
:使用
del
按索引删除元素,使用pop()
按索引删除(如果需要返回值),使用remove()
按值删除元素。后者需要搜索列表,如果列表中没有此类值,则会引发ValueError
。当从
n
元素列表中删除索引i
时,这些方法的计算复杂性是相关问题 更多 >
编程相关推荐