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])

28th Jul 2022, 7:40 AM
Rex
Rex - avatar
6 ответов
+ 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
28th Jul 2022, 11:14 AM
Amir
Amir - avatar
+ 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.
28th Jul 2022, 10:08 PM
Korkunç el Gato
Korkunç el Gato - avatar
+ 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)
28th Jul 2022, 8:13 AM
Felix Alcor
Felix Alcor - avatar
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
28th Jul 2022, 9:51 AM
Rik Wittkopp
Rik Wittkopp - avatar
0
Which operator is used for exponentiation in Python?
28th Aug 2024, 12:14 PM
Golu Yadav
Golu Yadav - avatar
0
Which operator is used for exponentiation in Python?
28th Aug 2024, 12:15 PM
Golu Yadav
Golu Yadav - avatar