You are not supposed to modify a list during iteration apparently. I can see the potential for problems, but I'm not sure when it is or isn't OK. For example, the code below seems to work fine:
import random
xs = [random.randint(-9,9) for _ in range(5)]
print(xs, sum(xs))
xs = [x * -1 for x in xs]
print(xs, sum(xs))
Is this OK because the list comprehension works differently to a normal for
loop?
This version seems equally unproblematic:
import random
xs = [random.randint(-9,9) for _ in range(5)]
print(xs, sum(xs))
for i in range(len(xs)):
xs[i] *= -1
print(xs, sum(xs))
So it looks like for this kind of use case there is no issue, unless I'm missing something.
What then are the situations when it is or isn't OK to modify a list while iterating over it?