+ 1

How is this working, I mean how is python executing

a = [0,1,2,3] for a[-1] in a: print(a[-1]) https://code.sololearn.com/cs2mWY3hjmOs/?ref=app

28th Apr 2021, 2:33 PM
KishanBGajera
KishanBGajera - avatar
9 Respostas
+ 5
https://code.sololearn.com/c2kNMIGR1HCC/?ref=app
28th Apr 2021, 2:52 PM
TOLUENE
TOLUENE - avatar
+ 2
The for loop works like this: for A in B: -> Get the elements from B one at a time and assign that value to A. A is a[-1] in your code, so the value gets assigned to the last element of a. Change the output to this: print(a) Then you can see the whole list in each iteration and see that only the last item changes. In the last step a[-1] is 2 from the previous step and gets assigned to itself, so output is 2 again
28th Apr 2021, 2:55 PM
Benjamin JĂŒrgens
Benjamin JĂŒrgens - avatar
+ 2
KishanBGajera take this modification of your code, it prints the complete list in the loop and the list is longer: a = [0,1,2,3,4,5] for a[-1] in a: print(a) Output is [0,1,2,3,4,0] [0,1,2,3,4,1] [0,1,2,3,4,2] [0,1,2,3,4,3] [0,1,2,3,4,4] [0,1,2,3,4,4] As you can see only the last element (a[-1]) changes. It is set by the loop. Read the loop like this: set a[-1] to each of the elements in a (one at a time) and run the code inside the loop
28th Apr 2021, 7:12 PM
Benjamin JĂŒrgens
Benjamin JĂŒrgens - avatar
+ 1
Benjamin JĂŒrgens please elaborate I'm not getting it 😕
28th Apr 2021, 2:57 PM
KishanBGajera
KishanBGajera - avatar
+ 1
Benjamin JĂŒrgens thanks 👍
29th Apr 2021, 2:08 AM
KishanBGajera
KishanBGajera - avatar
29th Apr 2021, 2:08 AM
KishanBGajera
KishanBGajera - avatar
0
It is a slicing Last element (a[-1]) because you have given in the range And your print a[-1] that is 2 and it will be assigned to itself so output is showing:- 0 1 2 2 Try- a = [0,1,2,3] for a[-1] in a: print(a[-1], end="")
30th Apr 2021, 5:06 AM
Utsav Singh
Utsav Singh - avatar
0
a = [0,1,2,3] for i in a: pass print(i) # everytime loop runs i is assigned corresponding value of list a from 0 index to -1 index . so it's final value is 3 a = [0,1,2,3] for a[-1] in a: print(a[-1]) # now consider same case with this one too . # first iteration a[-1] = a[0] = 0 # 2nd iteration a[-1] = a[1] = 1 # 3rd iteration a[-1] = a[2] = 2 # 4th iteration a[-1] = a[3] which is a[-1] actually . in 3rd iteration a[-1] was assigned value 2 . so this time a[-1] = a[3] = a[-1] =2 #by Nicolaus Copernicus
30th Apr 2021, 6:59 AM
Mr.Dark
Mr.Dark - avatar
0
Thanks Nicolaus easily explained this problem👍
30th Apr 2021, 7:00 AM
Mr.Dark
Mr.Dark - avatar