0

Why is my function 'increment' return different values for matrix that i create by other function and different for manual matrix?

n = 2
m = 3
indices = [[0,1],[1,1]]

def matrixpopulation(n,m):
    row=[]
    matrix=[]
    row+=(0  for _ in range(0,m))            
    matrix+=(row for _ in range(0,n))
    return matrix

def increment(indices,matrixa):
    for v,k in indices:
        for i in range(3):
            matrixa[v][i]+=1
        for i in range(2):  
            matrixa[i][k]+=1
    return matrixa

matrixa=matrixpopulation(n,m)
filled_matrix=increment(indices,matrixa)

print(matrixpopulation(n,m))
print(filled_matrix)

manualmatrix=[[0,0,0],[0,0,0]]
print(manualmatrix)
print(increment(indices,manualmatrix))
zephyrus
  • 1,266
  • 1
  • 12
  • 29
Alakeks
  • 3
  • 3

1 Answers1

1
matrix+=(row for _ in range(0,n))

When you make matrix here you actually add the reference to the same row n-times. When you modify some element in one 'row', all other rows are modified as well. For example:

a = [1, 2]
b = [a, a]
a[0] = 3

Check b now.

Alex Sveshnikov
  • 4,214
  • 1
  • 10
  • 26