In this post, you will learn a python program to rotate a matrix by 90 degrees in clockwise directions with a very simple explanation and algorithm.

So let us start learning…

## Rotate a Matrix by 90 Degrees (Clockwise)

Rotating a matrix by 90 degrees in the clockwise direction using python is a very simple task. You just have to do two simple steps, the first step is to transpose the given matrix and the second step is to reverse the rows of the transpose matrix.

Now let’s see the algorithm for the above steps

### Algorithm

From the above algorithm, we understood how to implement the python program to rotate a matrix by 90 degrees in a clockwise direction.

But before writing a program few programming concepts you have to know:

### Source Code

``````def rotate_matrix(matrix):
transposed = []
for row in zip(*matrix):
transposed.append(list(row))
rotated = []
for row in transposed:
rotated.append(row[::-1])
return rotated

# User input
rows = int(input('Enter number of rows: '))
cols  = int(input('Enter number of column: '))

matrix = [[int(input(f"column {j+1} -> ENter {i+1} element:")) for j in range(cols)] for i in range(rows) ]

print() # for new line
print('Given matrix :')

# print matrix
for row in matrix:
print(row)

# calling a function
rotate_90 = rotate_matrix(matrix)

print() # for new line
print('Matrix after rotated by 90 degree')

# print rotated matrix
for row in rotate_90:
print(row)``````

### Output-2 Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.