a = [0, 1, 2, 3]
for a[-1] in a:
print(a[-1])
I'm new to python, so can anyone explain the output of this code.
Output
0 1 2 2
a[-1]
indicates the last element 3
, so shouldn't the output be 3 3 3 3
?
a = [0, 1, 2, 3]
for a[-1] in a:
print(a[-1])
I'm new to python, so can anyone explain the output of this code.
Output
0 1 2 2
a[-1]
indicates the last element 3
, so shouldn't the output be 3 3 3 3
?
What happens is that a[-1] is being used as the variable in which each element is being stored. So for a[-1] in a: iterates over each element in a and stores the value in a[-1] i.e a[3]
As the last value being stored in a[3] is a[2] i.e 2 ... The output is 0,1,2,2 Hope it is clear now.
This code is equivalent tu the following: a = [0, 1, 2, 3]
for x in a:
a[-1] = x
print(a[-1])
so a[-1] is changing
This code should help clarify:
a = [0, 1, 2, 3]
for a[-1] in a:
print(a)
which outputs:
[0, 1, 2, 0]
[0, 1, 2, 1]
[0, 1, 2, 2]
[0, 1, 2, 2]
So what is happening is each time you go past the loop the list type is iterated upon starting at the start of your iterator (a
), which brings the next item of the list into memory at the name you declared (a[-1]
). Because you are changing the same thing you're iterating through, you get your unexpected result. Focusing on the last two outputs you can see that you write 2
into a[-1]
and then iterate so you're looking at a[4]
(which is also a[-1]
in this case) but that was just rewritten to 2
, hence your output.
What you probably wanted was something like:
a = [0, 1, 2, 3]
for foo in a:
print(foo)