Deletion of Python sequence (2) list

Time:2020-11-19

   1. Use the Del command to delete the elements at the specified position in the list

>>> s=[1,2,3,4]
>>> del s[1]
>>> s
[1, 3, 4]

2. Use the pop() method of the list to delete and return the elements at the specified (the default is the last) position. If the given index exceeds the range of the list, an exception will be thrown.

 

>>> a_list=list((1,2,3,4,5))
>>> a_list.pop()
5
>>> a_list
[1, 2, 3, 4]
>>> a_list.pop(1)
2
>>> a_list
[1, 3, 4]

3. Use the remove() method of the list object to delete the first occurrence of the specified element. If there is no element to be deleted in the list, an exception will be thrown.

>>> a_list=[1,3,5,7]
>>> a_list.remove(7)
>>> a_list
[1, 3, 5]

4. Clear clear the list