Difference between del, remove and pop on lists

前端 未结 12 2158
北海茫月
北海茫月 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 04:49

    Here is a detailed answer.

    del can be used for any class object whereas pop and remove and bounded to specific classes.

    For del

    Here are some examples

    >>> a = 5
    >>> b = "this is string"
    >>> c = 1.432
    >>> d = myClass()
    
    >>> del c
    >>> del a, b, d   # we can use comma separated objects
    

    We can override __del__ method in user-created classes.

    Specific uses with list

    >>> a = [1, 4, 2, 4, 12, 3, 0]
    >>> del a[4]
    >>> a
    [1, 4, 2, 4, 3, 0]
    
    >>> del a[1: 3]   # we can also use slicing for deleting range of indices
    >>> a
    [1, 4, 3, 0]
    

    For pop

    pop takes the index as a parameter and removes the element at that index

    Unlike del, pop when called on list object returns the value at that index

    >>> a = [1, 5, 3, 4, 7, 8]
    >>> a.pop(3)  # Will return the value at index 3
    4
    >>> a
    [1, 5, 3, 7, 8]
    

    For remove

    remove takes the parameter value and remove that value from the list.

    If multiple values are present will remove the first occurrence

    Note: Will throw ValueError if that value is not present

    >>> a = [1, 5, 3, 4, 2, 7, 5]
    >>> a.remove(5)  # removes first occurence of 5
    >>> a
    [1, 3, 4, 2, 7, 5]
    >>> a.remove(5)
    >>> a
    [1, 3, 4, 2, 7]
    

    Hope this answer is helpful.

提交回复
热议问题