+ 1

Python list how does it work?

In this code, why does rhis print 8? list = [1,1,2,3,5,8,13] print(list[list[4]])

26th Aug 2019, 4:56 AM
Steven a Harder
9 Answers
+ 10
list = [1,1,2,3,5,8,13] print(list[list[4]]) list[list[4]]== ==list[5]== ==8
26th Aug 2019, 5:06 AM
Mikhail Gorchanyuk
Mikhail Gorchanyuk - avatar
+ 2
no, it outputs 8 :) it is impossible for this code to output 4 because there is no 4 in the list :)
26th Aug 2019, 5:33 AM
Brave Tea
Brave Tea - avatar
+ 1
list[list[4]] means that the first list[?] needs a number. That number is found by checking the second list[] which is list[4]. list[4] is equal to 5 so the first list becomes list[5] list[5] is equal to 8
26th Aug 2019, 5:18 AM
Brave Tea
Brave Tea - avatar
+ 1
everytime you add a list[] you need to look at that number. always go right to left list 4 == 5 list 5 == 8 list 8 == 15
27th Aug 2019, 5:39 AM
Brave Tea
Brave Tea - avatar
0
I don't understand, I just tested the code in Playground, and it outputs 4, are you sure it outputs 5? (Edit) Ah, I see now, the OP had updated the Description with different code, well now it makes loads of sense LOL
26th Aug 2019, 5:25 AM
Ipang
0
Thanks for the heads-up Brave Tea Apparently I was viewing a cached version of the page, and the OP had modified it without any notice, in the cached version the list was [0,1,2,3,4,5]. That's why I got confused before I refresh the view LOL
26th Aug 2019, 6:19 AM
Ipang
0
:) no worries :)
26th Aug 2019, 6:29 AM
Brave Tea
Brave Tea - avatar
0
Sorry for not mentioning ubout the update. If 8 is in position 5 in the list, and the code should print position 4. I didnt get it yet. update: if i run this below code, i get 15. now im totaly confused list = [1,1,2,3,5,8,13,14,15] print(list[list[list[4]]])
27th Aug 2019, 5:16 AM
Steven a Harder
0
everytime you add a list[] you need to look at that number. always go right to left list 4 == 5 list 5 == 8 list 8 == 15
27th Sep 2019, 8:05 AM
Vicky Maurya
Vicky Maurya - avatar