SmithLogo

CSC 111

Introduction to Computer Science Through Programming

Smith Computer Science



Lecture Notes 18: 2D Lists and Nested Loops





Two-Dimensional structures (list of lists)

Imagine the following structre:

col 0 col 1 col 2
row 0 "0,0" "0,1" "0,2"
row 1 "1,0" "1,1" "1,2"
row 2 "2,0" "2,1" "2,2"


This structure is showing a grid of values, each located in a specific row and column (which are marked for clarity).

In that example, the values saved in each location (or cell) are the value's coordinates in the grid.



For example, in the following grid (wihtout the extra row and column markins),

"0,0" "0,1" "0,2"
"1,0" "1,1" "1,2"
"2,0" "2,1" "2,2"


the element "1,2" is at:




These types of structures are used all the time (to save data that can be classified under two categories or dimensions).
Think of "Students vs grades", or "x,y values", or "height vs weight" ratios.

How can we build one?

A list can be composed of the same types of elements ([1,2,3]) or of different types ([1, '2', False]).
In this class, we'll mostly use the same type of elements to keep things straightforward.

However, one of the types of things one can save in a list is another list!

In other words, we can have lists of lists!

The following is an example of a list of lists:

li = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print (li)


How to conceptualize this structure?

We need to think of this lists of lists in the following way:



This is a simplified visualization of how the elements are stored in the list li:



The following is the same list but with more of its parts explicitly highlighted:



However, when printed on the Python Tutor, the view is less pretty: Try it Here

Remember, the only important "layout" of the grid is the fact that we have an outer list with a lot of inner lists at each location.

Accessing 2D list elements

Since we have outer and inner lists, if we want an inner-list element (example: the element in row 1, column 2), we need to:
  1. Get the correct element (inner list) from the outer list (the inner list [4, 5, 6] at li[1])
  2. Get the correct element (number) from the selected inner list (example below)
We can do this in one or two steps:

1  
2  
3  
4  
5  
6  
7  
8  
9  
li = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print (li)

# in two steps
inner_li = li[1]
print("element at outer 1, inner 2:", inner_li[2])

# in one step
print("element at outer 1, inner 2:", li[1][2])


Check it out Here!

We'll work with these grids later today.




Nested Loops

Nested loops are loops done inside of other loops.

They are useful for many reasons, but a clue that we'll probably need one is when you have multiple dimensions to work through:

  1. For each student, get the average of all their grades
  2. For each word in a paragraph, check each one of its letters
  3. For each inner-list in an outer list, print out the inner-list's elements
  4. etc

Notation for nested loops

There is nothing to add!

You already know how to write a loop, simply write a loop inside a loop!




Combining 2D Lists and Nested Loops

A 2D list is a set of elements that changes in two dimensions (or a two levels).

We'll write a nested loop that prints all the elements inside a 2D list in the "grid pattern".

The Grid Print of a 2D List

Check out the following program:

 1  
 2  
 3  
 4  
 5  
 6  
 7  
 8  
 9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
def main():
    li = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    print ("ugly print: ", li)
    print()
    print ("grid print:")
    grid_print(li) # prints <argument> levels of numbers

def grid_print(li):
    n_rows = len(li)
    for row_idx in range(n_rows):
        n_cols = len(li[row_idx])
        for col_idx in range(n_cols):
            print(li[row_idx][col_idx], end=" ")
        print()        
   

if __name__ == "__main__":
    main()




Check it out Here!




Break and Continue

You can used two reserved words in a loop:



Examples: Check it out Weird printing of odd numbers
Check it out Escaping an infinite loop




Lab-like work

You are to build a program that initializes the following 2D-list of values:

8 9 10 7
7 9 8 7
5 7 6 5


This matrix of values represents the grades of 3 students: S1, S2, and S3 on four assignments: A1, A2, A3, and A4.

Use any means you think necessary to:
  1. Obtain the average grade for each student, and print it out
  2. Obtain the average grade for each assignment, and print it out




Homework

[Due for everyone]
Assignment 06 will be out Later Today (Due 10/25)

[Optional]
ZyBooks Sections 4.1 - 4.4