Use Python's pop and remove methods with caution

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.