Disclaimer: Reprint Please specify the source!!!
Python generally has two methods for deleting an element in the list, pop () and remove ().
If you delete a single element, use basically no problem, as follows.
1.pop () method, which passes the index of the element to be deleted:
x = [' A ', ' B ', ' C ', ' d ']x.pop (2) Print x------------------result:[' A ', ' B ', ' d ']
2. Remove () passes the element to be deleted, and if multiple elements are the same, the first one is deleted by default:
x = [' A ', ' B ', ' A ', ' C ', ' d ']x.remove (' a ') print x-----------------result:[' B ', ' A ', ' C ', ' d ']
If you want to recycle the elements that meet a certain condition, use caution!!
x = [' A ', ' B ', ' C ', ' d ']y = [' B ', ' C ']for i in X:if i in Y:x.remove (i) print x-----------------------result:[' A ', ' C ', ' d ']
x = [' A ', ' B ', ' C ', ' d ']y = [' B ', ' C ']for i in x:if i in y:idx = X.index (i) x.pop (idx) print x--------------result:[' A ', ' C ' , ' d ')
I think the main reason for this is that the pop and remove methods belong to the ' destructive operation ' (PS: Forgive me for my own definition), after X.remove (), the location of the original x in memory has been released, and re-applied memory to store the new X. It can be understood that X is not the original x, and the x passed in the For loop is the original x in memory, so after X.remove (i), the For loop cannot find X, and subsequent deletions cannot be completed. In order to complete the problem of looping the list element, I recommend the following method.
x = [' A ', ' B ', ' C ', ' d ']y = [' B ', ' c ']x_new = []for i in X:if I am not ' y:x_new.append (i) x = X_newprint x------------------ ----result:[' A ', ' d ']
Use Python's pop and remove methods with caution