0
What's the output of this code and explain. a=[1,2,3,4] for a[-1] in a: print(a[-1])
What's the output of this code and explain. a=[1,2,3,4] for a[-1] in a: print(a[-1])
6 Respostas
+ 2
If you copied your question from stackoverflow, you definitely know the answer.
Anyway, for those who don't know.
https://stackoverflow.com/questions/35046497/weird-for-loop-statement
+ 2
Amir's link explains all there's to explain but I think this being an assignment needs emphasis, because if you think of it as an equality that causes problems.
"for x in somelist" starts with:
x = somelist[0]
Left of the assignment is the variable, right of the assignment is the value assigned to the variable on left.
So substituting, you get
a[-1] = a[0]
so a[-1] is reassigned the value a[0] which is 1.
Rinse and repeat you get the whole output you posted. (edit: Felix posted)
There was a similar question a while back asked about dictionary, answered by Jayakrishna.
https://www.sololearn.com/Discuss/3043254/?ref=app
In short it's the position of a[-1] in the for loop that makes it the variable part of an assignment by that loop, and assignment is not the same thing as equality.
+ 1
The Output of that Code's:
1
2
3
3
I can't really explain why it's like that or what happens, but maybe tipping, can help you understand what happens there:
a=[1,2,3,4]
for a[-1] in a:
print(a)
0
I can't figure out the logic either.
I can see the outputs generated by playing with the code, but the logic behind it eludes me
0
Which operator is used for exponentiation in
Python?
0
Which operator is used for exponentiation in
Python?