Chapter 9 Lists

9.8 Lists of ListsΒΆ

A list can be an item in a list or tuple, in which case it is called a sub list.

>>> l=[[1,2,3],[4,5,6],[7,8,9]]
>>> l[0] # sub list
[1, 2, 3]
>>> l[0][0] # sub list item
1
>>> l[1][-1] # sub list item
6

A list of lists is called a nested list.

Many types of real-world data can be represented by a nested list. For example, the final examination results of a class can be represented by a nested list, where each sub list consists of the scores of 4 different subjects of a particular student. The trading records of a stock market can also be represented by a nested list, where each sub list consists of the daily closing prices of a particular stock. In mathematics, matrices can also be represented by nested list, where each sub list represents a particular row.

There are two general ways to solve problems that involve a nested list. The first is to treat each sub list as an atomic unit, and thereby process the nested list in the same way as processing a list of other objects. The second way is to use a nested loop to iterate over the items in the nested list.

Consider the problem of finding the total scores of the four subjects for each student in the final examination. The task is to write a function that that takes a nested list as the only argument, and returns a list that contains the sum of each sub list.

The problem can be solved by treating each sub list as an atomic unit, using the built-in function sum to calculate its total value. As a result, the idea of generalized summation can be applied to solve the problem: the return value is initialized to an empty list, and incrementally update by iterating through the input list. When each sub list is enumerated, its total value is added to the back of the return value. After the input list is exhausted, the return value contains the sum of each sub list. This solution can be written as the sumlists function below.

Now suppose that the problem is to find the average score of each student instead of the total score. The function sumlists can be modified slightly, calculating the average of each sub list by dividing the sum the number of items in the sub list. The function avglists below is an example implementation.

The expression float(sum(subl))/len(subl) may be difficult to understand. Alternatively, it can be modularized and implemented as a function. The example below uses the function avg to calculate the average of a list of numbers. It can make the avglists function easier to understand compared to the implementation of avglists above.

Now suppose that one needs to calculate the averaged score of all the subjects of all the students. The problem is to find the average of all the items of all the sublists in a nested list. It can be solved by calculating the sum of all the items of all the sub lists, and then dividing the sum by the total number of items of all the sub lists. The function avglistoflists below is an example implementation.

The function avglistsoflists above uses two variables, s and c, to maintain the sum and count of the items of the sub lists, respectively. The input list is iterated over so that s and c are updated incrementally. In this process, each sub list is treated as an atomic unit, processed by a function.

As mentioned in the beginning of the section, an alternative solution to nested list problems is to iterate through all the sub list items using nested loops. A nested loop can consist of two layers. The outer loop iterates through the list, enumerating each sub list. The inner loop iterates through a sub list, enumerating its items. In one execution of a nested loop, the outer loop is executed once, while the inner loop is executed once at each iteration of the outer loop.

For example, consider rewriting the avglists2 function above, replacing the function call avg in the function body with the function body of avg.

The functional avglists3 is different from the function avglists2 only in the loop body. avglists3 uses an inner loop to calculate the average of each sub list. Given a sub list subl, it uses the variable subs to keep the sum of subl, and the variable suba to keep its average. subs is initialized to 0, and updated incrementally by iterating through subl. suba is calculated by dividing subs by the length of subl. The five lines of statements commented with avg calculate subs and suba from a given subl, regardless of the rest of the control flow. The five lines of code are put inside the for loop over l, and repeatedly executed with subl being each sub list in l. As a result, the for loop over subl plays the role of an inner loop.

Nested loops can be used to iterate through all the items in all the sub lists in a nested list. It therefore provides an intuitive solution to the problem of finding the averaged score of the class. The function avglistoflists2 is an alternative implementation of avglistoflists using nested loops.

In the example above, s and c are used to hold the sum and count of items of all sub lists, respectively. A call to avglistoflist2 executes the outer loop (i.e. for subl in l) once. The body of the outer loop is repeated three times, with subl being [90, 95, 100, 100], [80, 70, 65, 71] and [95, 60, 75, 55], respectively. Each time the outer loop body is executed, the inner loop (for i in subl) is executed once, with the loop body being repeated four times. As a result, the statement c += 1 in the inner loop body is executed 12 times in total. Each time i being assigned the value of a different sub list item.

Loops can be nested in more than two levels, for the solution of more complex problems. The analysis and design of three-layer nested loops is similar to those of two-layer nested loops, and it is important to understand the functionality of the inner loop, so that it can be used correctly in combination of the outer loop. In case the program structure is too complex to understand, nested loops can be simplified by the use of function calls to replace inner loops, as illustrated by the contrast between avglists2 and avglists3.

Check your understanding

© Copyright 2024 GS Ng.

Next Section - 9.9 Copying Lists