Python Program to Rotate a Matrix by 90 Degrees
Intermediate · Matrices
Rotating a square matrix 90 degrees clockwise turns it a quarter turn to the right, so the first column, read from the bottom up, becomes the first row. Rotating an image works the same way, since an image is a grid of pixels. This program builds the rotated matrix with nested loops and prints both, row by row.
Program
Original matrix: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Rotated 90 degrees clockwise: 13 9 5 1 14 10 6 2 15 11 7 3 16 12 8 4
How it works
rotatedstarts as an n x n matrix of zeros; the list comprehension gives each row its own list.- In a clockwise turn, row
iof the original becomes columnn - 1 - iof the result: the top row becomes the right-hand column. - So the entry at
matrix[i][j]is copied torotated[j][n - 1 - i]. For example 1, at row 0, column 0, moves to row 0, column 3. show()prints a title and the matrix row by row, giving every number four spaces so the columns line up.
Other ways to write it
In place: transpose, then reverse each row
Rotated clockwise, in place: [7, 4, 1] [8, 5, 2] [9, 6, 3]
A transpose followed by reversing every row is the same as a clockwise turn, and it needs no second matrix. This is the usual interview answer.
Using zip() for both directions
Clockwise: [7, 4, 1] [8, 5, 2] [9, 6, 3] Anticlockwise: [3, 6, 9] [2, 5, 8] [1, 4, 7]
Reversing the rows and then taking the columns turns the matrix clockwise; taking the columns and then reversing their order turns it anticlockwise.
Try it yourself
Rotate the matrix twice and check that the result is the original turned upside down, 180 degrees.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises