Copy list before iteration


It is better to copy the list using list slices before the iteration starts.


examples/advanced/change_list_on_the_fly_copied.py
numbers = [1, 2, 3, 4]
for n in numbers[:]:
    print(n)
    if n == 2:
        numbers.remove(2)


print(numbers)

1
2
3
4
[1, 3, 4]