+ 2
Why is the output of below code "0 1 2 2" instead of "0 1 2 3"?
a = [0, 1, 2, 3] for a[-1] in a: print(a[-1]) # 0 1 2 2
2 Réponses
+ 3
Just think of python _for loop_ as of iterator yielding values.
"for x in a" means that you yield value from 'a' one by one and assign it to variable 'x'.
In this very case you are yielding values from 'a' list and assign them to variable which in its turn is the member of a the same very list.
just put 'print (a)' after 'print(a[-1])' in each iteration and you will see how the list changes:
a = [0, 1, 2, 3]
for a[-1] in a:
print(a[-1])
print(a)
>0
>[0, 1, 2, 0]
>1
>[0, 1, 2, 1]
>2
>[0, 1, 2, 2]
>2
>[0, 1, 2, 2]
So, every iteration you put yielded value to the last position of the list step by step from first to last.
But in final iteration you take the _last_ value in the list (wich is already 2) and put it back. That's why it looks like it doubles the last value.
I hope this cumbersome explanation makes it a littlr bit cleaner to you.
0
Sure it does,
Thanks a lot strawdog !