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.
1) 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:
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]
2) Example Grid
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]
3) Farming Functions
As an intern for the Farmers United Network (FUN) you've been given some spreadsheets of farm data for the amount of vegetables their farms harvested (in tons) last year. Conveniently, these spreadsheets already been converted to 2d arrays for you:
farm_data = [["farm name", "carrots", "potatoes"],
["veggiesRus", 100.5, 25],
["bestFarm", 150, 50.9],
["sadFarm", "no :(", 0]]
Given the starter file below, complete the functions in the file according to the descriptions in the comments.
Notes
- How can we make sure to only calculate totals / averages with entries that are ints or floats?
Next Exercise: -ing It!