+ 2

Can you explain the output of this code,please?

a=[0,1,2,3] For a[-1] in a: print(a[-1]) Output is 0 1 2 2

10th Mar 2020, 4:09 PM
Hamed
2 Answers
+ 7
In a regular for loop, when you write for x in whatever, x will take the value of each element. That's like writing: x = whatever[0] do stuff x = whatever[1] do stuff and so on. So here, you're assigning a new value to a[-1] with every iteration. So when you finally reach a[-1], you access 2, which is still stored there from the round before.
10th Mar 2020, 5:46 PM
HonFu
HonFu - avatar
+ 3
a [-1] is the last element of the array and in the loop it takes values ​​of the array itself: a = [ 0,1,2, 0 ] a = [ 0,1,2, 1 ] a = [ 0,1,2, 2 ] a = [ 0,1,2, 2 ]
10th Mar 2020, 5:47 PM
Vitaly Sokol
Vitaly Sokol - avatar