Matrices and grids · 1 / 15 Theory

Creating and traversing matrices

A matrix is a list of lists: each inner list is a row. It is accessed with m[row][column]. This lesson assumes you know the basics of lists; here you focus on traversing, transforming and reasoning about grids.

m = [
    [1, 2, 3],
    [4, 5, 6],
]
rows, columns = len(m), len(m[0])
print(rows, columns)                  # 2 3
print(m[1][2])                          # 6   (row 1, column 2)

for row in m:                          # walk by rows
    print(row)                         # [1, 2, 3] and then [4, 5, 6]

for i, row in enumerate(m):            # with indexes
    for j, value in enumerate(row):
        if value % 2 == 0:
            print((i, j), end=" ")      # (0, 1) (1, 0) (1, 2)
print()

print([list(column) for column in zip(*m)])   # [[1, 4], [2, 5], [3, 6]]   columns
print([row[1] for row in m])          # [2, 5]   a specific column
print(sum(map(sum, m)))                 # 21   sum of everything
print(max(max(row) for row in m))     # 6    global maximum

empty = [[0] * 3 for _ in range(2)]     # 2 rows x 3 columns de ceros
print(empty)                            # [[0, 0, 0], [0, 0, 0]]
  • len(m) is the number of rows and len(m[0]) the number of columns (if all rows have the same length).
  • zip(*m) transposes: it returns the columns as tuples.
  • To create an empty matrix use a comprehension ([[0] * c for _ in range(r)]), never [[0] * c] * r: it would repeat the same row (you saw this in Arrays).
  • Typical input: the first line with rows and columns and then one line per row, read with [input().split() for _ in range(r)].

Practice with Row and column sums and Transpose a matrix.