A list can contain other lists. With that you represent tables, boards and drawings: each inner list is a row.
marks = [
[7, 5, 9], # row 0
[4, 8, 6], # row 1
]
print(marks[0]) # [7, 5, 9]
print(marks[1][2]) # 6 (row 1, column 2)
print(len(marks)) # 2 rows
print(len(marks[0])) # 3 columns
You access with two indexes: matrix[row][column].
Going through a matrix
for row in marks:
for value in row:
print(value, end=" ")
print()
# 7 5 9
# 4 8 6
Averages per row
for i, row in enumerate(marks):
print(f"Average of row {i + 1}: {sum(row) / len(row)}")
It is the scheme of Two-dimensional array: each group of students is a row, and the average of each one is calculated.
Creating a matrix
The right way is with a list comprehension, which creates a new row on each turn:
rows, columns = 3, 4
board = [["X"] * columns for _ in range(rows)]
for row in board:
print("".join(row))
# XXXX
# XXXX
# XXXX
It is the basis of Two-dimensional array of chars.
The trap of [[x] * c] * r
bad = [[0] * 3] * 2 # both rows are the SAME list!
bad[0][0] = 9
print(bad) # [[9, 0, 0], [9, 0, 0]]
good = [[0] * 3 for _ in range(2)]
good[0][0] = 9
print(good) # [[9, 0, 0], [0, 0, 0]]
Drawing on a matrix
A drawing on the screen is a matrix of characters: first it is filled with spaces, then the cells that form the shape are changed and finally it is shown row by row. That is how Circle on screen works, and also the Banner command on Unix:
import math
side = 11
canvas = [[" "] * side for _ in range(side)]
center = side // 2
radius = 4
for degrees in range(360):
angle = math.radians(degrees)
x = center + round(radius * math.cos(angle))
y = center + round(radius * math.sin(angle))
canvas[y][x] = "*"
for row in canvas:
print("".join(row))
For each angle x and y are calculated with cosine and sine, rounded to integers and that cell is marked. In the banner, instead, the patterns of each letter stored in a table are looked up and written row by row.