Nested Lists

It is possible for the elements of a list to be lists themselves. Let’s consider a simple example.

metaList = [ 
    [4, 2], 
    ['a', 'b', 'c', 'd'], 
    [1.1, 2.2, 3.3] 
]

Notice that metalist is a list that contains three elements, each of which is also a list.

  • metaList[0] is a list of two int values, [4, 2].

  • metaList[1] is a list of four str, ['a', 'b', 'c', 'd'].

  • metaList[2] is a list of three float values, [1.1, 2.2, 3.3].

We can access elements of the inner lists by using two sets of square braces and two indices.

For example, since metaList[1] is the list ['a', 'b', 'c', 'd'], we can access the str 'c' with metaList[1][2].

print(metaList[1][2])
c

Example: Working with a List of Lists

In the cell below, we have created lists for 9 midwest states. Each state list contains the names of the cities in that state with a population of 100,000 or greater.

MO_list = ['Independence', 'Kansas City', 'Springfield', 'St. Louis']
IL_list = ['Aurora', 'Chicago', 'Joliet', 'Napierville', 'Peoria', 'Rockford', 'Springfield']
AR_list = ['Little Rock']
KS_list = ['Kansas City', 'Olathe', 'Overland Park', 'Topeka', 'Wichita']
IA_list = ['Cedar Rapids', 'Des Moines']
NE_list = ['Lincoln', 'Omaha']
OK_list = ['Norman', 'Oklahoma City', 'Tulsa']
TN_list = ['Chattanooga', 'Clarksville', 'Knoxville', 'Memphis', 'Nashville']
KY_list = ['Lexington', 'Louisville']

We will now create a list that contains each of these 9 lists as its elements.

state_list = [MO_list, IL_list, AR_list, KS_list, IA_list, 
              NE_list, OK_list, TN_list, KY_list]

Without referring directly to any of the 9 original lists, print out a list of the cities in Kansas with a population of 100,000 or greater.

print(state_list[3])
['Kansas City', 'Olathe', 'Overland Park', 'Topeka', 'Wichita']

Without referring directly to any of the 9 original lists, print out a list of the cities in Nebraska with a population of 100,000 or greater.

print(state_list[5])
['Lincoln', 'Omaha']

Using only the list cities_100K, print the element 'St. Louis'.

print(state_list[0][3])
St. Louis

Using only the list cities_100K, print the element 'Joliet'.

print(state_list[1][2])
Joliet