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