Nested Lists: Make a Grid in Python
A grid in Python is a nested list: a list of rows, where each row is a list of squares. Two indexes pick one square, the row first and the column second.
Before this lesson you should know how to read and change a list item by its index: see Change a List Item by Index.
A grid is a list of rows
Write one inner list per row, all the same length. One row per line makes the code look like the grid:
grid = [ ["~", "~", "~", "~"], ["~", ".", ".", "~"], ["~", "~", "~", "~"],]print(grid[1])print(len(grid))print(len(grid[1]))grid[1] is the second row, ['~', '.', '.', '~']. The grid has 3 rows, and
each row has 4 squares.
Read one square
Add a second index to pick a square inside the row. The first index is the
row, the second is the column, and both count from 0. In the grid above,
grid[1][2] is row 1, column 2: the "." before the last "~".
Changing one square
Assign to two indexes to replace one square. The other squares stay as they were:
grid = [ ["~", "~", "~", "~"], ["~", ".", ".", "~"], ["~", "~", "~", "~"],]print(grid[1][2])grid[1][2] = "X"print(grid[1])It printed ., then ['~', '.', 'X', '~']. Swapping the indexes, grid[2][1],
would change row 2 instead.
Print each row
A for loop over the grid gives you one row at a time, from the top:
grid = [ ["~", "~", "~"], ["~", ".", "~"],]for row in grid: print(row)Each row prints on its own line, as a list with brackets and quotes.
Draw one row as text
To print a row without brackets, build it into one string. Start with an empty string and add each square to it:
row = ["~", ".", ".", "~"]line = ""for square in row: line = line + squareprint(line)This prints ~..~. Put this loop inside a loop over the rows, and each row
draws in turn.
Visit every square by index
To know where each square is, loop over the row numbers with
range(len(grid)). Inside, loop over the column numbers of that row:
grid = [ ["a", "b"], ["c", "d"],]for row in range(len(grid)): for col in range(len(grid[row])): print(row, col, grid[row][col])This prints 0 0 a, 0 1 b, 1 0 c, then 1 1 d: every square, row by row
and left to right.
See also: Nested Data, Nested Loops & Ifs.
Your turn
Put "@" in row 2, column 0, then print row 2.
['@', '.', '.', '~']
grid = [ ["~", "~", "~", "~"], ["~", ".", ".", "~"], [".", ".", ".", "~"],]# change one square, then print row 2