-1

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)
Prune
  • 76,765
  • 14
  • 60
  • 81
KeyFive
  • 19
  • 5
  • You are creating a matrix of references to the same sublist. Change your initialization to `b = [[0] * len(a) for _ in range(len(a[0]))]` which will create independent lists. – user2390182 Dec 05 '20 at 08:36

1 Answers1

0

The question was answered in a comment. Thank you @schwobaseggl

All I had to do is change b to b = [[0] * len(a) for _ in range(len(a[0]))]

KeyFive
  • 19
  • 5