+ 2
Help me explain this code plz . Why output is 0122
a=[0,1,2,3] for a[-1] in a: print(a[-1])
3 Answers
+ 7
The loop runs 4 times and these things happens in every iteration
#1
a[3] becomes a[0] i.e a[3]=0 and we print a[-1] i.e 0
#2
a[3] becomes a[1] i.e a[3]=1 and we print it
#3
a[3] becomes a[2] i.e a[3]=2 and we print it
#4
a[3] becomes a[3] which is 2 and we print it
so we have printed 0 1 2 2
+ 3
Let me start with an example:
For example,
a=[0,1,2,3]
for i in a:
#some code
print(i)#3
Here the value of i is 3 because the last time in the for loop the value of i becomes 3. So the value of i is 3.
similar to your code:
a=[0,1,2,3]
for a[-1] in a:
print(a[-1])
I think you understand why the first 3 value is 012 because it just iterates and prints the value.
When you iterate with a[-1] the third time of iteration the value of a[-1](means the last value of the list) becomes 2 means the value of a[3] becomes 2.So when it iterates 4th time it prints the value of a[3] which is now 2 and so it prints 2 at the fourth time.
So in total it prints
0
1
2
2
+ 2
Thank you , guysđđđ