Gnijuohz
Gnijuohz

Reputation: 3364

incorrect output when trying to rotate a matrix in python

I'm trying to rotate a matrix(2-d list) in python by 90 degrees clockwise. Here is my code:

def rotate(matrix):
     length = len(matrix)
     new_matrix = [[0]*length]*length
     for i in range(length):
         for j in range(length):
             new_matrix[j][length-1-i] = matrix[i][j]
             print("new_matrix[",j,"][", length-1-i,"]", "is", new_matrix[j][length-1-i])
     for i in range(length):
         for j in range(length):
             print(new_matrix[i][j])
     return new_matrix
print(rotate([[1 ,2], [3, 4]]))

The idea is very simple, after rotating, the element with i, j as row number and column number will then have j, length-1-i as row and column numbers.

The print statement is used to verify I was doing it right. I tried [[1, 2], [3, 4]] and I got a wrong answer and a quite confusing output:

new_matrix[ 0 ][ 1 ] is 1
new_matrix[ 1 ][ 1 ] is 2
new_matrix[ 0 ][ 0 ] is 3
new_matrix[ 1 ][ 0 ] is 4
4
2
4
2
[[4, 2], [4, 2]]

It seems somehow values 1 and 3 got overwritten somehow. And when I tried [[1, 2, 3], [4, 5, 6], [7, 8, 8]] and new_matrix became [[9, 6, 3], [9, 6, 3], [9, 6, 3]]. So there is definitely something wrong here.

Any idea why?

Upvotes: 0

Views: 104

Answers (1)

Jared
Jared

Reputation: 26397

The problem in your code is this line,

new_matrix = [[0]*length]*length

It's not doing what you think - its actually creating a list of length number of the same inner list.

Replace it with something like the following which will create distinct inner lists,

new_matrix = [[0]*length for _ in range(length)]

Upvotes: 1

Related Questions