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