python--removing elements from a list with a for loop

Source: Internet
Author: User

For a run, there will be a pointer to the current loop of the element is which, at the beginning of the pointer to the NO. 0 element, and then get it, and then delete the No. 0 element, this time, the original 1th element will become No. 0, when the pointer moves backwards, pointing to the now 1th elements, The original 1th element is now the No. 0 element, so it was skipped during the loop deletion process.

To implement circular deletion, the first is that there are several elements in the list that loop several times, using pop () to remove from behind:

1 s = [one to one]2for   in range (0, Len (s)):3    s.pop ()4 Print (s)

The second method is to use another list to record what you want to delete, and then loop to delete it:

1 s = [one, one, one, 2 S_del = []3for in s:4    s_del.append (m)5 for in S_del:6     s.remove (i)7print(s)

The elements in the dict are not allowed to be deleted during the iteration, they can be an error, the key of the element to be deleted is saved in a list, and the data in the dictionary is deleted by looping the list.

PS: Because the deletion of elements will cause the index of the element to change, so it is prone to problems, try not to directly delete elements in the loop, you can add the elements to be removed to another collection and then bulk delete.

python--to remove elements from the list with a for loop

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.