Matrices and grids · 2 / 15 Theory

Transposing, rotating and mirroring

Almost every matrix transformation is written with zip(*m) (transpose) and the slicing [::-1] (reverse). Combining them gives rotations and mirrors.

m = [[1, 2, 3],
     [4, 5, 6]]

transposed = [list(c) for c in zip(*m)]
print(transposed)                       # [[1, 4], [2, 5], [3, 6]]

clockwise = [list(c) for c in zip(*m[::-1])]
print(clockwise)                     # [[4, 1], [5, 2], [6, 3]]

counterclockwise = [list(c) for c in zip(*m)][::-1]
print(counterclockwise)                 # [[3, 6], [2, 5], [1, 4]]

mirror_horizontal = [row[::-1] for row in m]
print(mirror_horizontal)                # [[3, 2, 1], [6, 5, 4]]

mirror_vertical = m[::-1]
print(mirror_vertical)                  # [[4, 5, 6], [1, 2, 3]]
TransformationExpression
Transposezip(*m)
Rotate 90° clockwisezip(*m[::-1])
Rotate 90° counterclockwiselist(zip(*m))[::-1]
Horizontal mirror[r[::-1] for r in m]
Vertical mirrorm[::-1]

zip returns tuples; if you need modifiable lists, convert them with list(...). A 180° rotation is two 90° rotations (or [r[::-1] for r in m[::-1]]). A matrix is symmetric if it equals its transpose.

You practice it in Rotate a matrix 90 degrees and Is it symmetric?.