0
What will be the output of the following python code snippet?
a=[0,1,2,3] for a [-1] in a: print (a[-1])
3 Answers
+ 3
Try out by yourself on Sololearn python compiler
+ 1
dhavasi s ,
to run this code without any issue, we have to use a proper indentation in the for loop first.
(the code itself does not really make any practical sense, it just looks like a code challenge.)
to get some output in this code is no problem, but since it is a bit difficult to understand what the code is really doing, a debugger running in step mode would be the preferred way to get a better insight.
what is this code doing:
> the code is iterating with a for loop through the elements of the list `a`, getting one element at a time.
> instead of using a loop variable, the value that it gets in each iteration will be assigned to the index position a[-1] of the list `a` (last element).
> it prints the value from list `a` that is stored at the index position [-1].
> this is repeated until the for loop is terminated.
+ 1
Lothar has it right.
You are editing the list as your for loop runs. It's a pretty chaotic process as you are modifying the list as you loop.
Try this variation to get a better feel for what's happening:
a=[0,1,2,3]
print (a[-1], a)
for a[-1] in a:
print (a[-1], a)
This will show you all the values in 'a' with each iteration.