Can't append matrix to array in python

Viewed 63

I've been writing some code in Python that should return an array of matrices from one starting matrix. Basically, you give the function a matrix and there are some if conditions that change certain numbers in it, then I add that matrix to the list of all matrices but it turns out that every time I add a new matrix I add the same exact one.

Here is my code:

arr = []
arr.append(staring_mat)

test = arr[:] # copying arr

matrix = staring_mat

for k in range(10):
  temporary = matrix
  for i in range(20):
    for j in range(20):
      number = do_something(i,j,temporary)
      if number < 15:
        temporary[i][j] = 12
      if number > 60:
        temporary[i][j] = 54
        .
        .
        .
  test.append(temporary)
  
  for num in range(len(test)):
    print(test[num])
    print('\n')
  
  matrix = temporary
  
 arr.extend(test)
1 Answers
matrix = staring_mat
temporary = matrix

By doing this you're creating a shallow copy, changes to the copy also affects the original. You should create a deep copy, here's the docs.

test = arr[:]

Here you're creating a deep copy.

Related