Working with a List of Lists

We said in ​Lists Are Heterogeneous​ that lists can contain any type of data. That means that they can contain other lists. A list whose items are lists is called a nested list. For example, the following nested list describes life expectancies in different countries:

​ ​>>>​​ ​​life​​ ​​=​​ ​​[[​​'Canada'​​,​​ ​​76.5],​​ ​​[​​'United States'​​,​​ ​​75.5],​​ ​​[​​'Mexico'​​,​​ ​​72.0]]​

Here is the memory model that results from execution of that assignment statement:

images/lists/nested_lists.png

Notice that each item in the outer list is itself a list of two items. We use the standard indexing notation to access the items in the outer list:

​ ​>>>​​ ​​life​​ ​​=​​ ​​[[​​'Canada'​​,​​ ​​76.5],​​ ​​[​​'United States'​​,​​ ​​75.5],​​ ​​[​​'Mexico'​​,​​ ​​72.0]]​
​ ​>>>​​ ​​life[0]​
​ ['Canada', 76.5]
​ ​>>>​​ ​​life[1]​
​ ['United States', 75.5]
​ ​>>>​​ ​​life[2]​
​ ['Mexico', 72.0]

Since each of these items is also a list, we can index it again, just as we can chain together method calls or nest function calls:

​ ​>>>​​ ​​life​​ ​​=​​ ​​[[​​'Canada'​​,​​ ​​76.5],​​ ​​[​​'United States'​​,​​ ​​75.5],​​ ​​[​​'Mexico'​​,​​ ​​72.0]]​
​ ​>>>​​ ​​life[1]​
​ ['United States', 75.5]
​ ​>>>​​ ​​life[1][0]​
​ 'United States'
​ ​>>>​​ ​​life[1][1]​
​ 75.5

We can also assign sublists to variables:

​ ​>>>​​ ​​life​​ ​​=​​ ​​[[​​'Canada'​​,​​ ​​76.5],​​ ​​[​​'United States'​​,​​ ​​75.5],​​ ​​[​​'Mexico'​​,​​ ​​72.0]]​
​ ​>>>​​ ​​canada​​ ​​=​​ ​​life[0]​
​ ​>>>​​ ​​canada​
​ ['Canada', 76.5]
​ ​>>>​​ ​​canada[0]​
​ 'Canada'
​ ​>>>​​ ​​canada[1]​
​ 76.5

Assigning a sublist to a variable creates an alias for that sublist:

images/lists/sublist_alias.png

As before, any change we make through the sublist reference will be seen when we access the main list, and vice versa:

​ ​>>>​​ ​​life​​ ​​=​​ ​​[[​​'Canada'​​,​​ ​​76.5],​​ ​​[​​'United States'​​,​​ ​​75.5],​​ ​​[​​'Mexico'​​,​​ ​​72.0]]​
​ ​>>>​​ ​​canada​​ ​​=​​ ​​life[0]​
​ ​>>>​​ ​​canada[1]​​ ​​=​​ ​​80.0​
​ ​>>>​​ ​​canada​
​ ['Canada', 80.0]
​ ​>>>​​ ​​life​
​ [['Canada', 80.0], ['United States', 75.5], ['Mexico', 72.0]]