a = [0, 1, 2, 3]
for a[-1] in a:
print(a[-1])
The output is 0 1 2 2
Why does a[-1] change with each iteration?
Your code is equivalent to:
a[-1] = a[0]
print(a[-1])
a[-1] = a[1]
print(a[-1])
a[-1] = a[2]
print(a[-1])
a[-1] = a[3]
print(a[-1])
Each time through the loop it assigns the value of the current list element to a[-1] and then prints it.
You are the changing a[-1] value while iterating. The iterating variable is a reference to objects in the iterable.
lst = [[1, 2], [3, 4]]
# ---> Iterating variable
# |
for val in lst:
val.append(55)
print(lst)
# [[1, 2, 55], [3, 4, 55]]
Because a is a reference to objects you're iterating over.
In your case, your iterating variable is a[-1] itself. So, you keep on changing a[-1]. You can debug by adding print(...) statements here.
a = [0, 1, 2, 3]
for a[-1] in a:
print(a)
[0, 1, 2, 0] # a[-1] == a[0]
[0, 1, 2, 1] # a[-1] == a[1]
[0, 1, 2, 2] # a[-1] == a[2]
[0, 1, 2, 2] # a[-1] == a[3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With