>>> A = [1,2,3,4,5,6]>>> for item in a: ... A.remove (item) ... >>> a[2, 4, 6]
Does it feel strange to see the code above? Intuitively, we just want to remove each element of queue a sequentially, in turn, and why the final result is [2,4,6]? If you have enough wit, you should guess what the reason is. For each for loop, the current time a. After the Remove (item) execution is complete, a is relatively shortened, and the element following the item complements the previously deleted position, resulting in the next element being deleted by the For loop. It can be seen that the use of a for statement presents an unpredictable risk if our iterative object is to change in the loop body.
>>> A = [1,2,3,4,5,6]>>> for item in a: ... Print (' Index: ', A.index (item), ' Content: ', item) ... A.remove (item) ... Index: 0 content:1index: 1 content:3index: 2 content:5>>> a[2, 4, 6]
python-the risk of a variable iterative object in a for loop risk on for loop while looping mutable iterable object