2-D Arrays

The questions below are due on Thursday June 17, 2021; 11:00:00 AM.
 
You are not logged in.

Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
Intro

We are often interested in representing 2-dimensional arrays (grids, etc.) in programs. Python does not have a built-in structure to represent 2-D arrays, but we can represent this structure using lists of lists.

Consider the following list:

array = [[1, 2, 3], [4, 5, 6]]

This list contains a representation for a 2-dimensional grid containing various elements:

123
456

We can access these elements by indexing into the outer-most list, and then into its children. If, for example, we were to do:

row = array[0]

row would then contain the first sublist ([1, 2, 3]). Graphically, we can view this as selecting the first row in the grid.

Then we can get a particular value with:

element = row[2]

This gets the element at index 2 from the list, which is 3. What we have done is grab the element in row 0 and column 2 by grabbing the element in the outer list at index 0, and then the element in that result at index 2.

We could also have done this in one step:

element = array[0][2]

Or, more generally, this expression evaluates to the element at a particular row r and column c:

array[r][c]
Example Grid

Consider the list of lists representing the following table, and assume it is stored in a variable called grid.

9573
2642
1084

What are the values of the following expressions? As before, if an expression would generate an error, type error in the box.

grid[1][1]

grid[2]

grid[0][3]

grid[2][2]

Array Functions

Now we're going to try to programatically access 2-d arrays (as lists of lists).

Getting a Row

Write a program that will print out the list representing the nth row of a 2-d array, when given array, a 2-d array (represented by a list of lists) and n, the index of the row we want (counting from 0).

The first lines of your programs should set up two variables to hold the inputs. For example:

array = [[1,0],[0,1]]
n = 0

  No file selected

Getting a Column

Write a program that will print out the list representing the nth column of a 2-d array, when given array, a 2-d array (represented by a list of lists) and n the index of the column we want (counting from 0).

The first lines of your programs should set up two variables to hold the inputs. For example:

array = [[1,0],[0,1]]
n = 0

  No file selected

Getting the Mean

Write a program that will print out a single number representing the mean of all of the elements of a 2-d array, when given array, a 2-d array (represented by a list of lists).

The first lines of your programs should set up one variable to hold the inputs. For example:

array = [[1,0],[0,1]]

  No file selected