Python deletes the correct procedure for the list being traversed by a for loop

Source: Internet
Author: User

Let's put a Python traversal exception that occurs:

1 ls =[1,2,3,4,5,6,7,8,9]2 for in ls:3     Print ("i", i)4     print("ls  ", ls)5     ls.remove (i)

Operation Result:

I 1ls [1, 2, 3, 4, 5, 6, 7, 8, 9]i 3ls [2, 3, 4, 5, 6, 7, 8, 9]i 5LS [2, 4, 5, 6, 7, 8, 9]i 7ls [2, 4, 6, 7, 8, 9]i 9ls [2] , 4, 6, 8, 9]

What I'm looking for is a traversal from a 1~9, but every time I skip an element, it makes me very surprised, curious, and wondering.

When the For loop is traversed, the object being traversed is also dynamic, not what I thought once I started traversing ls = [1,2,3,4,5,6,7,8,9], the list was fixed.

That's not true!!

This is a good example!

I think about the reason for guessing:

When the For loop iterates over an object, it is also traversed according to the number of elements in the list, and if you delete an element on the list itself, the number of elements changes, which is equivalent to moving the entire list to the left, but the index is then followed by 1-->2-->3. This is equivalent to the traversal of the element skipped a bit, the beginning of the exception error.

Python deletes the correct procedure for the list being traversed by 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.