In Python, modifying a list while iterating over it can lead to unexpected results. Consider the following code:
numbers = list(range(1, 50)) for i in numbers: if i < 20: numbers.remove(i) print(numbers)
Instead of removing numbers below 20, as intended, this code prints a list where all numbers below 20 are missing, along with 20 itself.
The issue stems from the fact that removing an item from a list shifts the position of subsequent items. As the loop progresses, the items being checked are no longer the expected ones, as the removed elements create "holes" in the list.
For instance, during the initial iteration, 1 is removed, but the next iteration does not check 2; instead, it checks 3 because the list has been shortened. This behavior continues, resulting in the incorrect output.
To avoid this problem, use alternative methods for altering lists during iteration, such as:
numbers = [n for n in numbers if n >= 20]
numbers[:] = (n for n in numbers if n >= 20)
for i, n in enumerate(numbers): if n < 20: numbers[i] = None numbers = [n for n in numbers if n is not None]
These techniques do not modify the list's length while iterating, ensuring correct item processing and the desired output.
The above is the detailed content of Why Does Modifying a Python List During Iteration Lead to Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!