Matrices: rows and columns
A table of numbers with rows and columns is called a matrix. In Python it's a list of rows, and each row is a list of numbers. Here are a café's sales for three days, one row per day and one column per product (coffee, tea and cake):
sales = [
[14, 6, 3],
[20, 4, 7],
[11, 9, 5],
]
print(sales[1][2])
sales[1][2] = 8
print(sales[1])
7
[20, 4, 8]The first index picks the row and the second the column, both counting from zero: sales[1][2] is the cakes of the second day. The same two indexes change one value.
Going through a matrix
A for loop over a matrix gets one row at a time. A second loop inside the first goes through the numbers of that row:
sales = [
[14, 6, 3],
[20, 4, 7],
[11, 9, 5],
]
total = 0
for row in sales:
for amount in row:
print(amount, end=" ")
total += amount
print()
print("Total:", total)
14 6 3
20 4 7
11 9 5
Total: 79A row and a column
One row is easy to get: it's sales[0], a list of its own. A column is spread over all the rows, at the same index in each of them. So a function for a column goes through the rows and takes one item from each:
def row_total(matrix: list, row_index: int) -> int:
return sum(matrix[row_index])
def column_total(matrix: list, column_index: int) -> int:
total = 0
for row in matrix:
total += row[column_index]
return total
sales = [
[14, 6, 3],
[20, 4, 7],
[11, 9, 5],
]
print("Day 1:", row_total(sales, 0))
print("Tea:", column_total(sales, 1))
Day 1: 23
Tea: 19Changing every value
This attempt to multiply every number by ten changes nothing:
grid = [[1, 2], [3, 4]]
for row in grid:
for number in row:
number *= 10
print(grid)
[[1, 2], [3, 4]]number *= 10 changes only the variable number, not the list it came from. To change the list, the loop needs the indexes. With range, the rows go from 0 to len(grid) - 1, and the columns of row i from 0 to len(grid[i]) - 1:
grid = [[1, 2], [3, 4]]
for i in range(len(grid)):
for j in range(len(grid[i])):
grid[i][j] *= 10
print(grid)
[[10, 20], [30, 40]]