0

please help me with a question, cause Im getting mad. I'm creating a 0-matrix, than tried to changed it's first element value to one, but it changes the whole column instead, and I don't get why:

    def id_mtrx(n):
        m = [[0]*n]*n
        m[0][0]=1
        return m

here is output:


    [[1, 0], [1, 0]]
while I was expecting:

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

It looks very simple, what can be wrong?
svfat
  • 3,273
  • 1
  • 15
  • 34
gwaka
  • 11
  • 1
    Hello, this is a classic problem (though I'm unable right now to find posts about the same problem): your matrix is created by doubling [0, 0], which actually creates 2 references to the SAME mutable (can be modified in-place) object. So when you modify it to [1, 0], both references now point to that. – Swifty Nov 04 '22 at 16:42

1 Answers1

0

You are creating multiple references to the same list object instead of creating new list, try:

n = 2
m = [[0 for _ in range(0, n)] for _ in range (0, n)]
m[0][0] = 1
print(m)

output is: [[1, 0], [0, 0]]

svfat
  • 3,273
  • 1
  • 15
  • 34