Comet has drawn the Larkspur test field as five strings, one per row. "Pip picks up the sample at row 0, column 2," she says. "So I change that star to a dot."
She types one line in the shell, and it stops with a TypeError.
Wren leans in. "What does the evidence say?" he asks. "The message says the string will not take a new character. We need a field we can change."
Nova projects the field as a stack of small square cells. "How can I help?" she asks. "Try turning each row into a list. Then point at a cell with two numbers."
"Lead programmer," Comet says, "which number comes first?"
The Larkspur test field is 5 rows by 6 columns. A dot is open ground, # is a rock, and * is a sample spot.
This is made-up data from the FieldSim story. Here is Comet's first try in the shell:
>>> row = "..*..#" >>> row[2] '*' >>> row[2] = "." Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: 'str' object does not support item assignment
A 2D grid can be stored as a list of lists. Each inner list is one row, and each item in a row is one cell.
In a grid, the first index is the row and the second is the column. So cells[2][4] means row 2, column 4.
# field_list.py
FIELD = [
"..*..#",
".#....",
"...#*.",
"*.....",
"..#..*",
]
cells = []
for row in FIELD:
cells.append(list(row))
print(len(cells), "rows")
print(len(cells[0]), "columns")
print(cells[0])
print(cells[2][4])
print(cells[4][2]) 5 rows 6 columns ['.', '.', '*', '.', '.', '#'] * #
| Statement | True or false? |
|---|---|
| In cells[r][c], the row comes first. | ? |
| cells[2][4] and cells[4][2] are the same cell. | ? |
| After list(row), one cell of that row can be changed. | ? |
| The test field has 6 rows. | ? |
Row first, then column. You will use that rule all week. Tomorrow you will walk every cell with nested loops.