A method of python operation list that is often used when recording LeetCode questions-deleting an element in the list.
There are generally three ways to delete elements from a list, del, pop(), remove().
- The del keyword method
del is to delete according to the index (element location), for example:
>>> str=[1,2,3,4,5,2,6]
>>> del str[1]
>>> str
>>> [1,3,4,5,2,6]
In addition to deleting a single element, del can also delete multiple elements by indexing slices, for example:
>>> str=[1,2,3,4,5,2,6]
>>> del str[1:4]
>>> str
>>> [1,5,2,6]
To be more thorough, del can delete the entire list, for example:
>>> str=[0,1,2,3,4,5,6]
>>> del str
>>> str #删除后,找不到对象
>>> Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
NameError: name 'str' is not defined
Note: del is to delete references (variables) instead of deleting objects (data), and objects are deleted by automatic garbage collection mechanism (GC).
- pop(): delete single or multiple elements, delete by index
>>> str=[0,1,2,3,4,5,6]
>>> str.pop(1) #pop删除时会返回被删除的元素
>>> str
>>> [0,2,3,4,5,6]
- remove() removes by value, removes a single element, removes the first element that meets the criteria
>>> str=[1,2,3,4,5,2,6]
>>> str.remove(2)
>>> str
>>> [1, 3, 4, 5, 2, 6] #此处删掉了列表中第一个值为‘2’的元素