+ 2

Help me explain this code plz . Why output is 0122

a=[0,1,2,3] for a[-1] in a: print(a[-1])

15th Jun 2021, 5:49 AM
TCorn
TCorn - avatar
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
15th Jun 2021, 6:47 AM
Prashanth Kumar
Prashanth Kumar - avatar
+ 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
15th Jun 2021, 6:34 AM
The future is now thanks to science
The future is now thanks to science - avatar
+ 2
Thank you , guys👍👍👍
15th Jun 2021, 7:42 AM
TCorn
TCorn - avatar