2-Dimensional Lists

Lists are useful as a standalone structure when containing integers, strings, and other types of data. This can be used to structure information in a useful way, that gives the programmer more capability to model real-world scenarios and represent complex information. Lists are also allowed to have more lists as elements within it. As an example, this is a perfectly valid list in Python:

grid = [ [1, 2], [3, 4] ]

The grid variable is a list. Each element within this list is yet another list. The value of grid[0] is [1, 2] and the value of grid[1] is [3, 4]. Lists that contain other lists as elements are referred to as 2-dimensional (2D) lists (Or more broadly, multi-dimensional lists). As a test of your understanding of lists and indexing, consider the following program:

x = grid[1][0]
y = grid[0][1]
print(x+y)
What will the program print?
1, 2, 3, 4
Incorrect. The program will only print out one number. What is that number?
4
Nope. This is close, as the program does print just one number, but it is not 4.
1
Nope. This is close, as the program does print just one number, but it is not 4.
5
Correct! grid[1][0] gives the value 3 from the 2D list, and puts it in x. grid[0][1] gives the value 2 from the 2D list, and puts it in y. Finally, the two values are summed and printed, resulting in 5.

2D Lists are both common and quite useful in computer programming. We can think of 2D lists as grids of values. The previous grid variable can be re-written as:

grid = [ [1, 2],
         [3, 4] ]

This is the exact same list as the previous one, but the formatting has been changed a bit to show the rectangular / grid structure. Another example, this time with more numbers in the list:

grid = [ [1, 2, 3, 4],
         [7, 2, 4, 1],
         [7, 2, 4, 4],
         [7, 0, 2, 1],
         [5, 2, 0, 1] ]

There are many types of information that 2D Lists are a natural structure to use for within a computer program. Consider the following concepts, and consider how using a 2D list when writing a related program would make sense.

Consider how a 2D List can be used for each concept.
Click to reveal the explanation.
The game of tic-tac-toe utilizes a 3x3 grid, where players alternate in placing X and O indicators. How might we use a 2D list if implementing a computer version of this game?
A 2D List should be used to represent the tic-tac-toe board. Initially, it could contain all empty string. As the players play, 'X' and 'O' Strings would be added to various positions. The board may look something like this, after a few moves:

board = [ [' ', 'X', 'O'],
          [' ', 'X', ' '],
          [' ', 'O', ' '] ]
          
In NBA basketball, each player who plays in a game has several stats, including number of points, number of rebounds and number of assists. How might this information be arranged for all players using a 2D list?
A 2D List should be used to represent this box score information. Each player would get a row (list) to himself. On each row would contain first the name of the player, then the points, rebounds, and assists, in that order. Thus, every row would have exactly 4 elements. The total number of rows would depend on how many players played in a game. As an example, the stats may look like this:

statistics = [
    ['Devin Booker', 21, 5, 7],
    ['Lebron James', 20, 4, 8],
    ['Stephen Curry', 24, 7, 9],
    ['Jimmy Butler', 10, 7, 4], ...]
               
An instructor at a school needs to write a program to keep track of the exam grades for each student in her class. The class she teaches has 4 total exams, each worth 25% of the class grade. How could a 2D list be used to store this information?
In this 2D list, each student in the class can have his or her own row. The first element of each row will be the name of the student. The following four elements will be integers, representing the grade for each of the four exams. The list would be structured as follows:

grades = [ 
    ['Jane Sammy', 80, 93, 84, 87],
    ['Karyn Small', 97, 98, 91, 92],
    ['Steve Carrol', 87, 75, 73, 81],
    ['Brady Richards', 70, 81, 91, 92], ...]
           

Consider the exam grades example from above. If there is a program that has a 2D list within it of this structure, then there may be calculations that the teacher would like to perform on the grades. One example would be final class grade calculation. If each exam is worth one-quarter of the grade, the average grade of these four represents the final class grade for each student. We could write a function that computes the final grade for each student. When the function is called, we would want it to print out the grade for each student, one per line. With a fully working version of this function, the following code:

grades = [ ['Jane Sammy', 80, 93, 84, 87],
           ['Karyn Small', 97, 98, 91, 92],
           ['Steve Carrol', 87, 75, 73, 81],
           ['Brady Richards', 70, 81, 91, 92]]
print_final_grades(grades)

Should print out:

Jane Sammy -> 86.0
Karyn Small -> 94.5
Steve Carrol -> 79.0
Brady Richards -> 83.5
Rearrange the lines of code to create a working print_final_grades function.
    for i in range(len(grades)):
def print_final_grades(grades):
        print(grades[i][0], '->', str(grade_sum/4)) 
        grade_sum = 0
        for gi in range(1, 5):
            grade_sum += grades[i][gi]

Another feature this instructor may want is to get the average grade performance on all exam attempts across all of her students. This would require calculating the average of all exam grades, not just the average for each row individually. This could be done with a few changes to the print_final_grades function above. Try copying this function into your IDE and writing the print_overall_exam_average function instead. After you’ve finished, come back here to see the solution.

Click to reveal the solution for print_overall_exam_average.
def print_overall_grade_average(grades):
    grade_sum = 0
    for i in range(len(grades)):
        for gi in range(1, 5):
            grade_sum += grades[i][gi]
    print('Average overall exam grade:', str(grade_sum/(len(grades)*4)))


PyFlo Home Complete Bookmark Next