Let’s say we have information about some students: their name, ID number, and their GPA (grade point average). We can use separate lists for each of these:
names = ["Phuong", "Federico", "Michele", "Steve"]
id_nums = [101345, 43617, 81882, 79315]
gpa = [3.9, 3.92, 3.85, 3.76]
There’s nothing wrong with this, but the data for each student really belongs together. It would be nice if we could put all the data into one list of four elements, where each element has the student name, ID, and GPA grouped together. It turns out that Python lets us do exactly that. We have already seen that lists can contain elements of different data types: [47, "blah", 37.5, True]
. Lists are also data types, so we can have a list that contains another list. That lets us write our student information as:
In this list, the element at each index is another list. Each element is called a sublist. A list sequence that contains one or more sublists is called a nested list.
Add the following line to the preceding program: print(len(students))
. Before you run the program, what do you think it will print? Will it print 12 (because there are 12 data items all together) or will it print 4 (the number of entries at the “top level” of the list)?
As you saw when you ran the program, len
returns the length of only the top-most list. In other words, sublists are considered to be a single item when counting the length of the list.
Subsection 9.21.1 Accessing Sublists and Sublist Elements
Looking at our student information, how would we access Federico’s GPA? We know that it is in the sublist at index 1 in the nested list, and the GPA is at index 2 in that sublist. We can use assignment to temporary variables:
Another easier way to access the element is to use the index operator [ ]
twice, giving the main list index first, followed by the sublist index:
This multiple-indexing works for any depth of nesting. Here are our students again, but this time, instead of the GPA, we have another sublist that gives their test scores on the two midterms and the final exam:
Subsection 9.21.3 Cloning Nested Lists
Unlike a simple list, you cannot clone a nested list with [:]
, as you can see from the following program:
The [:]
makes a new copy of the top level list, but the sublists are still references. Instead, you must import the copy
module and use its deepcopy
function: