pythonlistmatrixmultidimensional-arraylist-comprehension

Why are all rows of my matrix the same as the last row?


Can someone please help me find fault in my code? If I create a blank 2D matrix with static initial value, it returns the correct transposed matrix. Whereas if I create a blank matrix using a for loop, it is returning last row for all rows in the answer.

# Original Matrix :
[[1, 2, 3], 
[4, 5, 6], 
[7, 8, 9]]

# Expected Transpose :
[[1, 4, 7],
[2, 5, 8],
[3, 6, 9]]

# Actual Transpose :
[[3, 6, 9],
[3, 6, 9],
[3, 6, 9]]


# Transpose Matrix

def transpose_mtx(original):
    t_cols = len(original)
    t_rows = len(original[0])

    # creating a blank matrix with 0s of transpose shape
    row = [0 for _ in range(t_cols)]
    t_mtx = [row for _ in range(t_rows)]

    # t_mtx = [[0,0,0],[0,0,0], [0,0,0]]
    # if I keep this line instead, it returns correct answer
 
    # rows of original
    for i in range(len(original)):
        # columns of original
        for j in range(len(original[0])):
            # interchange items
            t_mtx[j][i] = original[i][j]
    
    return t_mtx


my_mtx = [[1,2, 3],
          [4, 5, 6],
          [7, 8, 9]]

print(transpose_mtx(my_mtx))

Solution

  • The problem is that you are using a list as an element of the list(as it should in the matrix), but the problem here is you are using all rows as the same list (that is row), and if you know that lists are mutable means they can update from anywhere and it will change for all reference of it.

    Now in this case the t_mtx is using all rows as the same reference list(row), which means each time you update any row it will update all the rows, that is why your all rows are the same as the last row.

    So here you can either create a new row each time or use the .copy() method to create a new copy of the row list.

    t_mtx = [row.copy() for _ in range(t_rows)]
    

    OUTPUT

    enter image description here

    Hope you understand, sorry for my bad English.