Difference between del, remove and pop on lists

前端 未结 12 2392
北海茫月
北海茫月 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:44

    Many best explanations are here but I will try my best to simplify more.

    Among all these methods, reverse & pop are postfix while delete is prefix.

    remove(): It used to remove first occurrence of element

    remove(i) => first occurrence of i value

    >>> a = [0, 2, 3, 2, 1, 4, 6, 5, 7]
    >>> a.remove(2)   # where i = 2
    >>> a
    [0, 3, 2, 1, 4, 6, 5, 7]
    

    pop(): It used to remove element if:

    unspecified

    pop() => from end of list

    >>>a.pop()
    >>>a
    [0, 3, 2, 1, 4, 6, 5]
    

    specified

    pop(index) => of index

    >>>a.pop(2)
    >>>a
    [0, 3, 1, 4, 6, 5]
    

    WARNING: Dangerous Method Ahead

    delete(): Its a prefix method.

    Keep an eye on two different syntax for same method: [] and (). It possesses power to:

    1.Delete index

    del a[index] => used to delete index and its associated value just like pop.

    >>>del a[1]
    >>>a
    [0, 1, 4, 6, 5]
    

    2.Delete values in range [index 1:index N]

    del a[0:3] => multiple values in range

    >>>del a[0:3]
    >>>a
    [6, 5]
    

    3.Last but not list, to delete whole list in one shot

    del (a) => as said above.

    >>>del (a)
    >>>a
    

    Hope this clarifies the confusion if any.

提交回复
热议问题