Python loop list Delete element problem

Source: Internet
Author: User

Someone will encounter this kind of problem, traverse the list, want to delete some elements of the list, after execution found that some are not deleted to,

such as the following code

a=[1,2,3,4,5,6]
Print (a) for in A: ifor i==4: a.remove (i)
Print (a)

The main thing to look at in code is to delete the 3 4 elements in the A list.

The result of the program is:

[1, 2, 3, 4, 5]

[1, 2, 4, 5]

The result is unsatisfactory, because we are walking

    • Seek went to the position of the 3 elements
    • If the Remove 3 element is judged
    • 3 This position is deleted after the position is empty, the following elements move forward, replacing the position of 3
    • Seek continued to go to the next, originally 4 elements, but the 4 elements moved forward, and then missed, seek went to the position of 5 elements

To avoid this problem you need to avoid the for loop, of course, the above example can have a lot of methods to delete, but when we encounter a case that can not avoid for the loop, you can save the deleted element to another list, and then delete it.

a=[1,2,3,4,5]d=[]print(a) for in A:    if  or i==4:        d.append (i)for in  D:    a.remove (i) Print (a) # [1, 2, 3, 4, 5] # [1, 2, 5]

Python loop list Delete element problem

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.