Difference between del, remove and pop on lists

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

    Since no-one else has mentioned it, note that del (unlike pop) allows the removal of a range of indexes because of list slicing:

    >>> lst = [3, 2, 2, 1]
    >>> del lst[1:]
    >>> lst
    [3]
    

    This also allows avoidance of an IndexError if the index is not in the list:

    >>> lst = [3, 2, 2, 1]
    >>> del lst[10:]
    >>> lst
    [3, 2, 2, 1]
    

提交回复
热议问题