Section 10.3 Nested List Traversal
Nested lists can be traversed the say way as other lists. However, the code to do so can easily get complicated and confusing. In this section let us examine several example programs that perform this task.
The following program concerns a list of lists of names. In some cases, we may want to take nested list data and "un-nest" it. To do this, we need to iterate through the outer list, and then construct another loop to iterate through each name in each sublist. In this program’s case, we are simply printing each name as we encounter it.
Nested lists can also be navigated by index rather than by value. This complicates the code somewhat, but gives us more flexibility for what can be done to each item. In this example program, we visit each name and turn it lowercase.
Note that in the above program it is very important that we use len(names[sublist_index])
in the second range call. Because the nested lists in this example do not have the same length, we have to check the length of each sublist when setting up our nested for loop bounds. If we do not do this carefully, then we can easily miss data or get an out of bounds exception. Consider a different, erroneous example:
Nested lists can be used in many different contexts, but one more common use is to model 2D grids of data. Here is one last example that treats nested lists as a 2D coordinate plane and finds the location of a single value in that plane. Note this example reverses the y axis, so y values increase as you travel downward. This is to match the indexing on the lists, though we could model this as a more familiar coordinate system with some small changes.
Check your understanding
Checkpoint 10.3.1.
What is printed by the following statements?
alist = [ [4, [True, False], 6, 8], [888, 999] ]
for a in alist:
for b in range(1, len(a)):
if type(a[b]) == type(a[b-1]):
print(a[b], end=" ")
8 999
- Yes, you are correct.
4 6 8 888 999
- You are correct that the code will treat the list with boolean value differently, but you are missing other aspects. Look again at the bounds of the inner loop.
4 True False 6 8 888 999
- This would be the output for a full traversal of the data. However, this code cannot fully traverse the data since it has three levels of nesting and the code only reaches two levels.
4 [True, False] 6 8 888 999
- This would be the correct output if the code traversed two levels of nesting and printed everything. However, the if statement is also doing something here.
You have attempted
of
activities on this page.