Conor Igoe
Conor Igoe

Reputation: 69

Copying Matrices in Python

I want to copy a matrix so that changing a value in the copy doesn't change the value in the original. I understand why the following is incorrect:

matrix1 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
matrix2 = matrix1
matrix2[0][0] = 9
matrix2  # [[9, 2, 3], [1, 2, 3], [1, 2, 3]]
matrix1  # [[9, 2, 3], [1, 2, 3], [1, 2, 3]]
matrix2 is matrix1  # True

My original approach was this:

matrix1 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
matrix2 = matrix1[:][:]
matrix2[0][0] = 9
matrix2  # [[9, 2, 3], [1, 2, 3], [1, 2, 3]]
matrix1  # [[9, 2, 3], [1, 2, 3], [1, 2, 3]]
matrix2 is matrix1  # False

In the second code excerpt, matrix1 and matrix2 do not reference the same object. Why then, do changes in matrix2 still affect matrix1? I was of the understanding that if they are separate objects, then changing one will not change the other, which is the reason why the slicing notation works for a 1-dimensional array.

Upvotes: 2

Views: 4049

Answers (1)

Javier
Javier

Reputation: 2776

The first [:] produces a copy of the outermost list. The second [:] produces another copy of the outermost list.

What you want to do is called a "deep copy". Take a look at the copy module: https://docs.python.org/dev/library/copy.html#copy.deepcopy

Upvotes: 1

Related Questions