1

The immutable and mutable is causing problem.

I was trying to rotate the matrix by 90 degree clockwise without changing the argument passed in function.

def rotate(m):
 rm=[[0]*len(m)]*(len(m))
 print("m:",m)
 print("rm:",rm)
 for j in range(len(rm)):
 for i in range(len(rm)):
 k=m[j][i]
 y=(len(rm)-j-1)
 rm[i][y] = k
 print(i," ",len(rm)-j-1," ",rm[i][(len(rm)-j-1)])
 print("m:",m)
 print("rm:",rm)
 return rm
 print(rotate([[1,2,3],[4,5,6],[7,8,9]]))

I expect the rm should be "[[7, 4, 1], [8, 5, 2], [9, 6, 3]]" but it is "[[9, 6, 3], [9, 6, 3], [9, 6, 3]]" at the end of function.

Harshal Parekh
6,0374 gold badges25 silver badges46 bronze badges
asked Aug 17, 2019 at 23:13

1 Answer 1

2

You are seeing the error, because the line rm=[[0]*len(m)]*(len(m)). Try to change it for:

rm = [[0 for _ in range(len(m))] for _ in range(len(m))]

Note: The above function can be rewritten as:

l = [[1,2,3],[4,5,6],[7,8,9]]
def rotate(lst):
 return [list(val[::-1]) for val in zip(*lst)]
print(rotate(l))

This prints:

[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
answered Aug 18, 2019 at 4:37
1
  • Wow. I think this is something that is important and non-obvious (maybe it is obvious to everyone but me, I dunno). rm1=[[0]*3]*3 (OPs approach) and rm2=[[0 for _ in range(3)] for _ in range(3)] (Andrej's approach) will produce lists rm1 and rm2 that look alike and compare equal, but behave differently. Assigning rm1[0][0]=33 will result in list [[33, 0, 0], [33, 0, 0], [33, 0, 0]] whereas assigning rm2[0][0]=44 will result in list [[44, 0, 0], [0, 0, 0], [0, 0, 0]]. Commented Aug 18, 2019 at 5:21

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.