2

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 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.