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

发布于 2021-02-02 23:19:23

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

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

关注者
0
被浏览
65
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    是的,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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看