0
0
PythonHow-ToBeginner · 3 min read

How to Rotate a Matrix 90 Degrees in Python Easily

To rotate a matrix 90 degrees clockwise in Python, you can use zip(*matrix[::-1]) to reverse the rows and then transpose the matrix. This creates a new rotated matrix without modifying the original.
📐

Syntax

To rotate a matrix 90 degrees clockwise, use the pattern rotated = list(zip(*matrix[::-1])).

  • matrix[::-1] reverses the rows of the matrix.
  • *matrix[::-1] unpacks the reversed rows as arguments.
  • zip(...) groups elements from each row to form columns of the rotated matrix.
  • list(...) converts the zipped object back to a list of tuples representing rows.
python
rotated = list(zip(*matrix[::-1]))
💻

Example

This example shows how to rotate a 3x3 matrix 90 degrees clockwise using the syntax above.

python
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

rotated = list(zip(*matrix[::-1]))

for row in rotated:
    print(list(row))
Output
[[7, 4, 1] [8, 5, 2] [9, 6, 3]]
⚠️

Common Pitfalls

One common mistake is to try to rotate the matrix by transposing only without reversing rows, which results in a mirrored matrix, not a rotated one.

Another is modifying the original matrix in place without careful indexing, which can cause data loss.

python
# Wrong way: just transpose
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
rotated_wrong = list(zip(*matrix))

# Right way: reverse rows then transpose
rotated_right = list(zip(*matrix[::-1]))

print("Wrong rotation:")
for row in rotated_wrong:
    print(list(row))

print("Right rotation:")
for row in rotated_right:
    print(list(row))
Output
Wrong rotation: [1, 4, 7] [2, 5, 8] [3, 6, 9] Right rotation: [7, 4, 1] [8, 5, 2] [9, 6, 3]
📊

Quick Reference

Summary tips for rotating a matrix 90 degrees clockwise in Python:

  • Reverse the rows of the matrix with matrix[::-1].
  • Use zip(*...) to transpose the reversed matrix.
  • Convert the zipped result to a list for easy use.
  • Remember this creates a new rotated matrix; original stays unchanged.

Key Takeaways

Rotate a matrix 90 degrees clockwise by reversing rows and then transposing with zip.
Use list(zip(*matrix[::-1])) to get the rotated matrix as a list of tuples.
Avoid just transposing without reversing rows to prevent incorrect rotation.
This method creates a new matrix and does not change the original matrix.
Print rows as lists for clearer output since zip returns tuples.