a = [0, 1, 2, 3] for a[-1] in a: print(a[-1])

a = [0, 1, 2, 3]
for a[-1] in a:
print(a[-1])

 

You can see the loop like these instructions:

a[-1] = a[0] # a = [0, 1, 2, 0]
print(a[-1]) # 0
a[-1] = a[1] # a = [0, 1, 2, 1]
print(a[-1]) # 1
a[-1] = a[2] # a = [0, 1, 2, 2]
print(a[-1]) # 2
a[-1] = a[3] # a = [0, 1, 2, 2]
print(a[-1]) # 2
So, when you are on the third element, then 2 is stored to a[-1] (which value is 1, but was 0 before and 3 on start).

Finally, when it comes to the last element (and the end of the iteration), the last value stored into a[-1] is 2 which explains why it is printed twice.

 

Leave a Reply

Your email address will not be published. Required fields are marked *