Difference between del, remove and pop on lists

前端 未结 12 2130
北海茫月
北海茫月 2020-11-22 04:20
>>> a=[1,2,3]
>>> a.remove(2)
>>> a
[1, 3]
>>> a=[1,2,3]
>>> del a[1]
>>> a
[1, 3]
>>> a= [1,2,3]
>         


        
12条回答
  •  隐瞒了意图╮
    2020-11-22 04:49

    The remove operation on a list is given a value to remove. It searches the list to find an item with that value and deletes the first matching item it finds. It is an error if there is no matching item, raises a ValueError.

    >>> x = [1, 0, 0, 0, 3, 4, 5]
    >>> x.remove(4)
    >>> x
    [1, 0, 0, 0, 3, 5]
    >>> del x[7]
    Traceback (most recent call last):
      File "", line 1, in 
        del x[7]
    IndexError: list assignment index out of range
    

    The del statement can be used to delete an entire list. If you have a specific list item as your argument to del (e.g. listname[7] to specifically reference the 8th item in the list), it'll just delete that item. It is even possible to delete a "slice" from a list. It is an error if there index out of range, raises a IndexError.

    >>> x = [1, 2, 3, 4]
    >>> del x[3]
    >>> x
    [1, 2, 3]
    >>> del x[4]
    Traceback (most recent call last):
      File "", line 1, in 
        del x[4]
    IndexError: list assignment index out of range
    

    The usual use of pop is to delete the last item from a list as you use the list as a stack. Unlike del, pop returns the value that it popped off the list. You can optionally give an index value to pop and pop from other than the end of the list (e.g listname.pop(0) will delete the first item from the list and return that first item as its result). You can use this to make the list behave like a queue, but there are library routines available that can provide queue operations with better performance than pop(0) does. It is an error if there index out of range, raises a IndexError.

    >>> x = [1, 2, 3] 
    >>> x.pop(2) 
    3 
    >>> x 
    [1, 2]
    >>> x.pop(4)
    Traceback (most recent call last):
      File "", line 1, in 
        x.pop(4)
    IndexError: pop index out of range
    

    See collections.deque for more details.

提交回复
热议问题