No Reading Questions
No Quiz
2D Lists
We already know that lists can contain other lists
a_list = [[1], [2, 3], [4, 5, 6]]
- 2D lists are lists containing lists with additional restrictions
- All sub lists are the same size and all elements are the same type
So the above lists is not a 2D list, but the following is
a_list = [[1, 2, 3], [4, 5, 6]]
- There are two sublists, both of length 3 and both only containing ints
- In memory, a 2D list looks more like the way we defined it above
But working with them can be simplified if we think of them as a grid, or matrix
a_list = [[1, 2, 3], [4, 5, 6]]
- The grid consists of rows and columns
So to access an element of the 2D you must specify the row and column of the element
row = 1 col = 2 print(a_list[row][col])
Rows
Because each sub list is a row, can get an entire row of a 2D list with array access
a_row = a_list[1]
Can also get the number of columns by getting the length of a row
num_cols = len(a_list[0])
And can use loops to iterate over a row of the list
row = 1 for col in range(len(a_list[0])): print(a_list[row][col])
Columns
Because each sub-list is a row, the number of rows is the length of the array
num_rows = len(a_list)
Iterating over a column similar to iterating over a row
col = 1 for row in range(len(a_list)): print(a_list[row][col])
Getting a column is a little trickier, you can’t get a column with a single array access operation, instead need to iterate
a_col = [] col = 1 for row in range(len(a_list)): a_col.append(a_list[row][col])