What is the output of this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

What is the output of this code?

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

3rd Mar 2020, 6:15 AM
APC (Inactive for a while)
APC (Inactive for a while) - avatar
4 Answers
+ 7
So a = [0,1,2,3] is the list what for loop does in for i in a: print (i) is that it assigns each values of a to i (or you can say iterates through a) and prints 0 1 2 3 But here it is for a[-1] in a: print(a[-1]) So for the first time a[-1] = 0 a = [0,1,2,0] So 0 is printed because it will print the last element of the list. For second time a[-1] = 1 a = [0,1,2,1] so 1 is printed Third time a[-1] = 2 a = [0,1,2,2] so 2 is printed But for the third time a[-1] = 2 because the last element has now become 2 a = [0,1,2,2] so 2 is printed again. In the end output is 0 1 2 2 And the loop is ended here. You can check this by putting print(a) in the loop.
3rd Mar 2020, 6:39 AM
Utkarsh Sharma
Utkarsh Sharma - avatar
+ 6
3rd Mar 2020, 6:19 AM
APC (Inactive for a while)
APC (Inactive for a while) - avatar
+ 1
Utkarsh Sharma very good
3rd Mar 2020, 7:09 AM
UraL
0
In the end output is 0 1 2 2 // a = [0,1,2,3] for a[-1] in a: print(a[-1]) To know more about Python Code visit here: https://www.cromacampus.com/courses/python-training-in-noida/
5th Mar 2020, 9:21 AM
sonu singh
sonu singh - avatar