This is infuriating me. I have to make a function that finds the transpose of a function. I want to initialize the tranposed matrix early by making it all 0. I do that by typing: b = [ [0] * len(a)] * len(a[0])
Whenever I do that, it just fills up with the bottom row of the original matrix: [[-9, -7, 10, 3], [-9, -7, 10, 3], [-9, -7, 10, 3]]
But when I do: [ [0,0,0,0], [0,0,0,0], [0,0,0,0] ]
, it works just fine!! How is this possible?
My function is:
def matrix_transpose(a):
"""
-------------------------------------------------------
Transpose the contents of matrix a.
Use: b = matrix_transpose(a):
-------------------------------------------------------
Parameters:
a - a 2D list (2D list of ?)
Returns:
b - the transposed matrix (2D list of ?)
------------------------------------------------------
"""
b = [ [0] * len(a)] * len(a[0])
for i in range(len(a)):
for j in range(len(a[0])):
b[j][i] = a[i][j]
return b
a = [ [-5, -4, -9], [-5, 0, -7], [6, 9, 10], [5, -9, 3] ]
b = matrix_transpose(a)
print(b)