7.1 2D Lists
You’ve learned how to create and use lists in previous lessons. A list is a one-dimensional data structure. In this lesson, you’ll learn how to create a 2D list, or a grid. In Python, a really convenient way to store a grid of values is as a list of lists.
The example below creates a list full of more lists.
In this example, the variable my_grid
is the main list and there are 8 one-dimensional lists inside this list. You can access any of the one-dimensional lists by using an index, the same way you have always accessed anything in a list.
When the program below is run, what will be printed by the first print statement is the 0th list in the list of lists. Python accesses index 0 in my_grid
and returns and prints that element. The element is, in this case, another list.
You can use another set of square brackets to be even more specific. If you’d like to access a particular integer, you should first specify which list it is in, and then specify where it is in that list.
In the second print statement, Python accesses the list at index 0, and then within that list, accesses the integer at index 1. This can be done to access any individual integer in the list. If you included the command print(my_grid[3][4])
, Python would then go to the list in the 3rd index and then the integer in the 4th index. This would print the number 3.
Slices can be used in 2D lists as well. They work the same way as with 1D lists.
In the example below, Python accesses the list at index 3 and then returns a slice from that list starting at index 4.
You can also take a slice of the whole 2D grid. In the example below, all lists up to but not including index 2 be will be returned. This results in a list of lists that is smaller than our original list of lists.
The append function can also be used to create and add to a list of lists. The example below starts out with an empty list. More lists are then appended to it.
If you’d like to print each list on a separate line, you can use a for loop over the grid in order to print out each 1D list individually.
Finally, you can also use a nested for loop in order to print out each number individually.
-
Incorrect
Correct
No Answer was selected
Invalid Answer
What does the following program print?
my_grid = [[2, 5, 7, 10], [-3, "hello", 9, "hi"], ["hello", "hi", "hello", "hi"]] print(my_grid[1:])
For this exercise, you create a grid that has 1’s on the top two rows and the bottom two rows, and 0’s on the middle two rows. The grid should look like this:
Let’s try to do this in steps.
Step 1: Create a 6x6 grid that holds all 0’s.
Step 2: Using a nested for
loop, make the top two rows all 1’s, along with the bottom two rows. The middle two rows should be all 0’s. This should be done after you’ve already set everything to 0.
Step 3: Use the provided print_board
function to print your grid.