This is because in Python, this:
a = [0, 1, 2, 3]
for i in a:
... statements ...
can be understood as this:
a = [0, 1, 2, 3]
it = iter(a)
i = next(it)
... statements ...
i = next(it)
... statements ...
i = next(it)
... statements ...
i = next(it)
... statements ...
Now if you replace i
by a[index]
, then you end up replacing a[index]
by the last element you iterated over, which is the last element in your list.