简体   繁体   中英

Printing 2 lists in python

I'm trying to learn python and I was using an app. In one of the tests it asked me for the output of:

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

I couldn't find the solution and I looked at the solution, It was 8. But the problem is, it doesn't show you why. I did a little search on this subject on google and stackoverflow but I couldn't find why. Maybe I don't know how to ask this question. Anyways, as I said I'm pretty new to this stuff so the title probably doesn't fit the question but I really don't know how to write my question in 5 words. It would be great if you help.

You can work from the inside to the outside of these calls. That line is equivalent to the following:

value1 = list[4]   # this is 5 
value2 = list[value1]   # this is 8
print(value2)

You want to find the value of List[List[4]]

First, let's substitute the inner part List[4] and it will equal 5 as we count from 0 in python so you have:

list[0] = 1
list[1] = 1
list[2] = 2
list[3] = 3
list[4] = 5

and so on.

So now after getting the inner part we can easily figure out the overall question as follows:

 List[List[4]] = List[5] = 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM