+ 2

Python Challenge Problem

I am confusing with this code. a = [1,2,3,4,5] for a[-1] in a: print(a[-1]) #How to explain this output? ''' 1 2 3 4 4 ''' https://code.sololearn.com/cTD1wuLKrMg0/?ref=app

21st Apr 2020, 2:21 AM
RainStorm
RainStorm - avatar
4 Answers
+ 4
During the execution of this code 2 main things happen: 1. Treating a[-1] as a variable of for loop. 2. Multiple assignment of the last element of list( a ) i.e 5. Expressed by a[-1] See statement.( for a[-1] in a ). In the 1st execution it assigns a[-1] .i.e 5 to 1 ( a[ -1 ] = 1 ), then the loop prints a[ -1 ] treating it a loop variable assigned to 1st element of list a. Therefore variable a[-1] prints 1. These two things continue and when the loop reaches at 4 just before last element. The list looks like [1,2,3,4,3] that follows: 👉 a[ -1 ] as an index. That reads a[ -1 ] = 4("3 = 4" means last element assigned to 4 because the loop is in 4th element) 👉 And a[ -1 ] as a variable of for loop (here loop is in 4th element therefore the variable is equals to 4). And so it prints 4. Now the list looks something like this [1,2,3,4,4] In last execution the index a[ -1 ] = 4 i.e 4 is assigned to 4. And so the variable a[ -1 ] is printed which is 4. I tried my best to make is understandable.👍
21st Apr 2020, 3:10 AM
Tricker
+ 2
This is absolutely terrible questions 😭😭.
21st Apr 2020, 3:21 AM
RainStorm
RainStorm - avatar
+ 2
I hate it.
21st Apr 2020, 3:21 AM
RainStorm
RainStorm - avatar
+ 1
Hey PythonPip your explain is the easist to understand it. Thanks for sharing your thought. I have the blast to coding.
21st Apr 2020, 3:15 AM
RainStorm
RainStorm - avatar