I'm trying to tranpose a matrix in Python 3.x without using numpy. For some reason, I'm having problems with the assignment of new_matrix[col_num][row_num]
. For example, if I create a new instance of Matrix like test = Matrix([[1,2,3,],[4,5,6],[7,8,9]])
, the first time it goes through the inner for loop, new_matrix becomes [[1,None,None],[1,None,None],[1,None,None]]
instead of [[1,None,None],[None,None,None],[None,None,None]]
. I can't figure out why this is happening and why it's assigning a value to ALL the first elements of lists.
class Matrix:
def __init__(self, matrix):
self.matrix = matrix
def transpose(self):
new_matrix = [[None] * len(self.matrix[0])] * len(self.matrix)
row_num = 0
for row_num in range(len(self.matrix)):
for col_num in range(len(self.matrix[0])):
print(new_matrix[col_num][row_num])
print(new_matrix)
#assignment assigning more than one variable
new_matrix[col_num][row_num] = self.matrix[row_num][col_num]
print(new_matrix[col_num][row_num])
print(new_matrix)
col_num = 0
return new_matrix