+ 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]])
9 Answers
+ 10
list = [1,1,2,3,5,8,13]
print(list[list[4]])
list[list[4]]==
==list[5]==
==8
+ 2
no, it outputs 8 :) it is impossible for this code to output 4 because there is no 4 in the list :)
+ 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
+ 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
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
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
0
:) no worries :)
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]]])
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