0

Can someone explain this for me, I don't understand why? or how? the answer is 8.

list = [1,1,2,3,5,8,13] print(list[list[4]] Result: 8

22nd May 2021, 7:57 AM
Will Lim
Will Lim - avatar
12 Réponses
+ 5
Besides all of these things, I would like to mention something else: ▪︎the code that was initially shown has an issue, since: print(list[list[4]] a round closing bracket is missing at the end of the line ▪︎an other issue that the identifyer name <list> should not be used, as there is a class and a function in python with the same name. This will overwrite the existing class. here is an example that demonstrates what happens if this fact is ignored: #list = [1,1,2,3,5,8,13] #print(list[list[4]]) print(list('abcd')) # result is normally ['a', 'b', 'c', 'd'] ▪︎first try: run this code as it is, so the result will be ['a', 'b', 'c', 'd'] ▪︎second try: remove the <#> from line 1 and 2, and run the code again ▪︎the result will be a error message: 《 TypeError: 'list' object is not callable 》 the end of the story is, that this issue might not raise an error during developing or testing a code, but can appear when using the app. to catch this bug can be a real nightmare.
22nd May 2021, 9:13 AM
Lothar
Lothar - avatar
+ 4
First inner list is evaluated which returns 5 , now that value 5 act as an index for outer list . list[list[4]] is reduced to list[5] which returns 8 not 4.
22nd May 2021, 8:00 AM
Abhay
Abhay - avatar
+ 2
Will Lim you forgot to edit your question as well .
22nd May 2021, 8:08 AM
Abhay
Abhay - avatar
+ 2
Will Lim list[3] == 3 so list[list[3]] == list[3] == 3 list[4] == 5 so list[list[4]] == list[5] == 8
22nd May 2021, 8:40 AM
visph
visph - avatar
+ 2
Finally I understand. Thanks visph Lothar Abhay .
22nd May 2021, 9:56 AM
Will Lim
Will Lim - avatar
+ 1
Abhay OP just have edited its description ;P
22nd May 2021, 8:01 AM
visph
visph - avatar
0
Abhay :D I even didn't noticed that point (passing my way while seeing your answer) ;P
22nd May 2021, 8:12 AM
visph
visph - avatar
0
Abhay Sorry for editing the question, now can explain one more time more clearly cause I'm still don't understand.
22nd May 2021, 8:29 AM
Will Lim
Will Lim - avatar
0
Will Lim don't forgot that indices start at zero (list[0] is the first item) ;)
22nd May 2021, 8:31 AM
visph
visph - avatar
0
visph yes but I try to change list[list [4]] to list[list[3]] the result is 3 not 5, if as what yours mention above the result should be 5 but why I get 3
22nd May 2021, 8:36 AM
Will Lim
Will Lim - avatar
0
first list [4] will result in 5 so list [5] will give you op 8
23rd May 2021, 7:41 AM
MEGH
0
We know that list[4] is 5 and then the program says list[list[4]] Thats the same thing as saying list[5] list[5] is 8 Thats my answer, hope u can use ir ;)
23rd May 2021, 4:02 PM
6hpxq9
6hpxq9 - avatar