+ 3

Explanation of code

I came through a quiz question in Python which I am unable to understand.Anybody please explain it:) s=["red","green","blue","white"] p=[1,2,3,4] r="" for i in range(len (s)): r+=s[i][p[i]] print(r)

24th Jul 2018, 11:13 AM
Ashita Udhani
Ashita Udhani - avatar
4 Réponses
+ 3
Try to read parentheses from inside out! i-Loop begins with 0; so what's p[i]? Answer's p[0]. And what's that? Looking at list p... Ah, 1! So the confusing line now reads [0][1], which is a lot easier. And what is that? Well, list s, element 0, and within that element the position 1... Ah, 'e'! And then you do that for the whole loop. Again, always from inside out!
24th Jul 2018, 4:35 PM
HonFu
HonFu - avatar
+ 1
s[i] is the i-th element of the list s. Same for p[i]. Now for any string, say, "Sololearn", "Sololearn"[k] is the k-th character of the string. Thus, s[0][p[0]]="red"[p[0]]="red"[1]="e" Similarly, s[1][p[1]], s[2][p[2]], and s[3][p[3]] are also "e". Thus the for loop is concatenating "e" with r four times. Since r was initially an empty string, the final result is "eeee". Does that make sense?
24th Jul 2018, 11:23 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 1
The output: "eeee" for i in range(4): r+=s[i][p[i]] First : r+=s[1][p[1]] == r+=red[1] == r+="e" Second : r+=s[2][p[2]] == r+=green[2] == r+="e" Third : r+=s[3][p[3]] == r+=blue[3] == r+="e" Forth : r+=s[4][p[4]] == r+=white[4] == r+="e" Then r="eeee"
24th Jul 2018, 11:27 AM
Sousou
Sousou - avatar
+ 1
for i in range(len(s)): len(s)=4 means 0=>i<4 when i=0 then p[i]=1 and then s[i][p[i]] means s[0][1]=e ,because p[i]=1 r=r+s[i][p[i]]= e because r='' and s[i][p[i]] so r=e when i=1 then p[i]=2 and s[i][p[i]] means s[1][2] because p[i]=2 so s[1][2]=e and then r=r+s[i][p[i]] r=e and s[i][p[i]]=e so r=ee and then so on.....
24th Jul 2018, 11:28 AM
Maninder $ingh
Maninder $ingh - avatar