for loops and iterating through lists – how does “for a[-1] in a:” work?

While doing for a[-1] in a, you actually iterate through the list and temporary store the value of the current element into 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 Comment