Computer Science · Ch 9 — Lists
Nested Lists
Nested Lists
When a list appears as an element of another list, the inner list is called a nested list. Nesting lets one list carry structured sub-groups of data alongside ordinary elements.
A nested list is just an element
In the list below, most elements are plain values, but the element at index 4 is itself a list:
>>> mix = [3, 8, 'x', 'y', [21, 22, 23], 6, 'z']
>>> mix[4] # the fifth element of mix is itself a list
[21, 22, 23]
A single index treats the nested list as one whole element — mix[4] returns the entire inner list, not any value inside it.
Reaching inside — two indices
To access an element of the nested list, specify two indices: mix[i][j].
- The first index
iselects the desired nested list from the outer list. - The second index
jselects the desired element within that nested list.
>>> mix[4][1] # index 4 gives the nested list [21, 22, 23],
22 # index 1 gives its second element
Read mix[4][1] left to right: mix[4] first evaluates to [21, 22, 23], and then [1] indexes into that result.
Where nesting is useful
A nested list is the natural way to keep a record's related values bundled together — for example a list of [subject, code] pairs (seen back in Section 9.1), or a student record that stores a sub-list of marks inside a larger list of details. The double-index notation then retrieves any single field: the first index picks the record or group, the second picks the value within it. …