0

I have a matrix which i want to transpose and I've done this before and it's worked, but it's only today while I've been going through my code and updating it that it has suddenly stopped working. I really don't know why, as it has worked fine before. Here's the main bit of code

class Matrix:
    def __init__(self, cols, rows):
        self.cols = cols
        self.rows = rows
        self.matrix = [[0]*self.rows]]*self.cols

    def transpose(self):
        transposed_matrix = Matrix(self.rows, self.cols)

        for i in range(self.cols):
            for j in range(self.rows):
                transposed_matrix.matrix[j][i] = self.matrix[i][j]

        return transposed_matrix

So say I have a matrix like this

[
     [0, 1, 1, 0, 0, 0]
     [1, -1, 0, 0, 0, -1]
     [-1, -1, 0, -1, 1, 0]
     [-1, 1, -1, -1, -1, 0]
]

I'm expecting

[
    [0, 1, -1, -1]
    [1, -1, -1, 1]
    [1, 0, 0, -1, -1]
    [0, 0, -1, -1]
    [0, 0, 1, -1]
    [0, -1, 0, 0]
]

But instead I'm getting

[
    [0, -1, 0, 0]
    [0, -1, 0, 0]
    [0, -1, 0, 0]
    [0, -1, 0, 0]
    [0, -1, 0, 0]
    [0, -1, 0, 0]
]

If you can help shed some light on this then that would be really appreciated

martineau
  • 119,623
  • 25
  • 170
  • 301
Aguy
  • 169
  • 11
  • 1
    change `[[0]*self.rows]]*self.cols` into `[[0]*self.rows] for i in range(self.cols)]` and google "How does Python referencing work" – Szabolcs Dombi Jan 10 '19 at 14:01
  • `transposed-matrix` is not a valid variable name, you can't use `-` in variables as it is the subtraction operator. Please do test the code you post in questions. – Martijn Pieters Jan 10 '19 at 14:04
  • @SzabolcsDombi Thank you, it's now fixed. Although i don't understand how that made a difference. Could you please explain it – Aguy Jan 10 '19 at 14:05
  • 2
    See the duplicate; multiplication doesn't create copies of contained objects; all you get is repeated references. A list comprehension on the other hand executes the expression at the start each iteration, creating a new list object each time. – Martijn Pieters Jan 10 '19 at 14:05
  • @MartijnPieters sorry i didn't realize i thought i put a "_" not a "-" – Aguy Jan 10 '19 at 14:06

0 Answers0