In Python, how do I rotate a matrix 90 degrees counterclockwise?

Viewed 30536
>>> def rotate_matrix( k: List[List[int]]):
    """
    For example, if I have:
    m = [[1,2,3],
         [2,3,3],
         [5,4,3]]
    rotate_matrix(m) should give me [[3,3,3],[2,3,4],[1,2,5]]. 
    """

Edit: Preferably without numpy.

10 Answers

Here is the counter clockwise matrix rotation as one line in pure python (i.e., without numpy):

new_matrix = [[m[j][i] for j in range(len(m))] for i in range(len(m[0])-1,-1,-1)]

If you want to do this in a function, then

def rotate_matrix( m ):
    return [[m[j][i] for j in range(len(m))] for i in range(len(m[0])-1,-1,-1)]

and either way, the result for

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

is

[[3, 3, 3], [2, 3, 4], [1, 2, 5]]

Aside, if you want the usual transpose, then the simple one line pure python version is

[[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]

You could use the numpy function rot90

import numpy as np
m = np.array([[1,2,3],
         [2,3,3],
         [5,4,3]])

def rotate_matrix(mat):
    return np.rot90(mat)
def rotate_90_degree_anticlckwise(matrix):
    new_matrix = []
    for i in range(len(matrix[0]), 0, -1):
        new_matrix.append(list(map(lambda x: x[i-1], matrix)))

    return new_matrix


def rotate_90_degree_clckwise(matrix):
    new_matrix = []
    for i in range(len(matrix[0])):
        li = list(map(lambda x: x[i], matrix))
        li.reverse()
        new_matrix.append(li)

    return new_matrix

def rotate_90_degree_clckwise_by_zip_method(matrix):
    return list(list(x)[::-1] for x in zip(*matrix))

#solution1

print(list(list(x) for x in zip(*m))[::-1])

#solution2

print([[x[i] for x in m] for i in range(len(m))][::-1])

#solution3

r = []
i = 0
for row in m:
  listToAdd = [item[i] for item in m]
  r.append(listToAdd)
  i +=1
print(r[::-1])

Look at this code. This is the way to rotate any matrix by 90 degrees using scratch

[This is the code to have a matrix rotated by 90 degrees][1]

    n = input("enter input:")
    l =[]

    while (n !=""):
    
        l.append(n.split(" "))
        n = input("enter input:")
        l1=[]
    for i in range(len(l[0])):
        l1.append([])
    for j in range (len(l1)):
        for p in range(len(l)):
           l1[j].append(l[p][-(j+1)])

    for s in l1:
         print(*s)
'''


  [1]: https://i.stack.imgur.com/c8jHC.png

Just flip the matrix vertically, then switch the upper-right triangle with the lower-left triangle

def rotate_matrix_ccw(mat):
    if mat is None:
        return None
    n = len(mat)
    if n == 1:
        return mat
    for i in range(n):
        if len(mat[i]) != n:
            raise Exception("Matrix must be square")
    # flip the matrix vertically
    for j in range(n // 2):
        for i in range(n):
            mat[i][j], mat[i][n - 1 - j] = mat[i][n - 1 - j], mat[i][j]
    # switch the upper-right triangle with the lower-left triangle
    for i in range(n):
        for j in range(i):
            mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
    return mat

You can loop through the original matrix and create a new one. This is my approach for counterclockwise, for the other way it would be similar. This doesn't require it to be a square.

def left_rotate(mat):
    if not mat: return []
    colcount = len(mat[0])

    # Initialize empty lists
    new = [list() for _ in range(colcount)]
    # Go through the rows, append elements one by one
    for row in mat:
        for j in range(colcount):
            new[j].append(row[colcount - 1 - j])
    return new

Example:

>>> print(left_rotate([[1, 2], [3, 4], [5, 6]]))
[[2, 4, 6], [1, 3, 5]]

flip vertically (left to right) then transpose:

m = [[1,2,3],
     [2,3,3],
     [5,4,3]]
print([list(x) for x in zip(*[x[::-1] for x in m])])
def rotateMatrix(self, matrix):
    for i in range(len(matrix)):
        for j in range(i):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

    matrix.reverse()

Rotate matrix anti-clockwise 90deg (In-place)

def rotate(matrix):
    for i in range(len(matrix) - 1, -1, -1):
        for j in range(i):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    matrix.reverse()

Rotate matrix clockwise 90deg (In-place)

def rotate(matrix):
    matrix.reverse()
    for i in range(len(matrix)):
        for j in range(i):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
Related