6.7) Nested Lists
A nested list is a list containing a list. We’ve seen examples of list of strings, a list of lists is much the same.
>>> L=[[1,2,3],[4,5,6]] >>> L[0] # the first element of L is also a list [1, 2, 3] >>> L[1] # and so is the second element of L [4, 5, 6]
If you want to refer to the third element of the second list in L:
>>>L[1][2] 6
To remember which index comes first, think of breaking down the process like this:
>>> sublist=L[1] >>> sublist[2] 6
So you first look for the second list L[1] and then for the third element in that list [2].
See a nested list in action with the Pythontutor.com visualisation tool.
[advanced_iframe securitykey="cdcd195854f0661ec0561aa6e33a487eadfbcbcc" src="http://pythontutor.com/iframe-embed.html#code=L%3D%5B%5B1,2,3%5D,%5B4,5,6%5D%5D%0AL1%3DL%5B0%5D++%23+the+first+element+of+L+is+also+a+list%0AL2%3DL%5B1%5D++%23+and+so+is+the+second+element+of+L%0AL1%5B2%5D%3D30%0A%0AM1%3D%5B%22a%22,%22b%22,%22c%22%5D%0AM2%3D%5B1,2,3%5D++++%0AM%3D%5BM1,M2%5D&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=2&curInstr=0"]