Difference between del, remove and pop on lists

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

    Use del to remove an element by index, pop() to remove it by index if you need the returned value, and remove() to delete an element by value. The last requires searching the list, and raises ValueError if no such value occurs in the list.

    When deleting index i from a list of n elements, the computational complexities of these methods are

    del     O(n - i)
    pop     O(n - i)
    remove  O(n)
    

提交回复
热议问题