Cheap VPS host selection
Provide server host evaluation information

Python deletes an element in the list

In Python, there are three methods to delete an element in the list: remove, pop, and del:

1. remove: delete a single element, delete the first qualified element, and delete by value

For example:

>>> str=[1,2,3,4,5,2,6] >>> str.remove(2)
>>> str
[1, 3, 4, 5, 2, 6]

2. pop: delete single or multiple elements, and delete by bit (delete according to index)

>>> str=[0,1,2,3,4,5,6] >>>Str.pop (1) # pop When deleting, the deleted element will be returned
>>> str
[0, 2, 3, 4, 5, 6] >>> str2=[‘abc’,’bcd’,’dce’] >>> str2.pop(2)
‘dce’
>>> str2
[‘abc’, ‘bcd’]

3. del: It is deleted according to the index (element location)

For example:

>>> str=[1,2,3,4,5,2,6] >>> str2.pop(2)
[1, 3, 4, 5, 2, 6] >>> str2=[‘abc’,’bcd’,’dce’] >>> del str2[1] >>> str2
[‘abc’, ‘dce’]

In addition, del can delete values within the specified range.

#Python learning exchange QQ group: 778463939
>>> str=[0,1,2,3,4,5,6] >>>Del str [2:4] # Delete the elements starting from the second element and ending at the fourth element (but excluding the trailing element)
>>> str
[0, 1, 4, 5, 6]

Del can also delete the entire data object (list, collection, etc.)

>>> str=[0,1,2,3,4,5,6] >>> del str
>>>Str # Object not found after deletion
Traceback (most recent call last):
File “”, line 1, in
str
NameError: name ‘str’ is not defined

Note: del deletes references (variables) rather than objects (data). Objects are deleted by the automatic garbage collection mechanism (GC).

Supplement: disguised method for deleting elements

print(‘s1_2:’, s1)
‘s3:’, s3)
s1 = (1, 2, 3, 4, 5, 6)
s2 = (2, 3, 5)
s3 = [] for i in s1:
if i not in s2:
s3.append(i)
print(‘s1_1:’, s1)
s1 = s3
print(‘s2:’, s2)
print(‘s3:’, s3)
print(‘s1_2:’, s1)

Original address: https://mp.weixin.qq.com/s/9abEltGpvofy0X5HWbn_AA

Do not reprint without permission: Cheap VPS evaluation » Python deletes an element in the list