2-D Arrays
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.
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:
1 | 2 | 3 |
4 | 5 | 6 |
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]
Consider the list of lists representing the following table, and assume it is stored in a variable called grid
.
9 | 5 | 7 | 3 |
2 | 6 | 4 | 2 |
1 | 0 | 8 | 4 |
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]
Now we're going to try to programatically access 2-d arrays (as lists of lists).
Write a program that will print out the list representing the n
th 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
Write a program that will print out the list representing the n
th 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
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]]