0

I'm aware that simply assigning one list to another preexisting list gives it the same address e.g.

x = [1, 2] y = x y[0] = 3 print(x, y)

gives the output

[3, 2] [3, 2]

and to prevent this, it has to be written as such...

y = list(x), y = x[:], etc.

However, this doesn't seem to work in my case...

for i in range(layer_rot):
            for r in range(l - 1, n_rows - l + 1):
                if r == l - 1:
                    result[r][n_col - l] = int(ref_matrix[r + 1][n_col - l])
                elif r == n_rows - l:
                    result[r][l - 1] = int(ref_matrix[r - 1][l - 1])
                else:
                    result[r][l - 1] = int(ref_matrix[r - 1][l - 1])
                    result[r][n_col - l] = int(ref_matrix[r + 1][n_col - l])

            ...

            ref_matrix = result[:] # Assume ref_matrix is initialized correctly before the first iteration of the outer loop

I'd like ref_matrix to be simply a copy of result, but when I change result in the conditional statements, I notice that ref_matrix changes along with it. I've checked their id's, but they're both different as expected. Any thoughts?

1 Answers1

1

You're using a nested list of lists, but ref_matrix = result[:] only makes a shallow copy of the top level list, so you have a new list containing the same lists as the first.

The simplest solution here is to just switch to a full deep copy:

import copy

then replace:

ref_matrix = result[:]

with:

ref_matrix = copy.deepcopy(result)

No matter how deeply nested your lists (and how mutable their contents), this will ensure all mutable elements are fully dissociated from the original list.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271