How about if we rewrote it like this?
We can ‘unpack’ my_list in stages in order to make sense of it:
What do you think this will print?
Let’s make it a little more obvious:
We could then try this:
This produces:
Some observations:
i in my_list using either for i in my_list (every element in turn) or my_list[i] (one element only).j in list i using for j in i (every element in turn) or i[j] (one element only).Does that mean we can also do this:
So if we write:
Then:
my_list[i] returns [1,2,3] (because i==0 and the first list is [1,2,3]), andmy_list[i][j] returns 2 (because j==1 and the [1,2,3][1]==2).Similarly, my_list[2] grabs the third list ([7,8,9]) and then my_list[2][2] tells Python to get the third item in that third list (i.e. 9).
If I rewrite the list this way perhaps it looks a little more useful?
my_cities = [
['London', 51.5072, 0.1275, +0],
['New York', 40.7127, 74.0059, -5],
['Tokyo', 35.6833, 139.6833, +8]
]Now we have something that is starting to look like data!
This is also a legitimate list in Python.
There is no real limit to how many lists you can nest inside of other lists, but it’s hard to make sense of:
my_cities[0][1][4][1][8]!

LoLs • Jon Reades