I've got matrix = [[1,2,3],[4,5,6],[7,8,9]] and matrix2=matrix. Now I want to delete first row from matrix2 i.e., matrix2.remove(matrix[0]).
But I am getting this
>>> matrix2.remove(matrix2[0])
>>> matrix2
[[4, 5, 6], [7, 8, 9]]
>>> matrix
[[4, 5, 6], [7, 8, 9]]
First row of matrix is also removed. Can anyone explain this? And how to remove first row from matrix2 without altering matrix
Try:
>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>>
>>> # make matrix2 a (shallow) copy of matrix
>>> matrix2 = matrix[:]
>>> matrix2.remove(matrix[0])
>>> print(matrix2)
[[4, 5, 6], [7, 8, 9]]
Hmm ... why is that? Its because the statement matrix2 = matrix does not "copy" a value ... it merely means that the name matrix2 points to the exact same value as the name matrix.
To actually create a (shallow) copy of a list, we can just slice it as matrix2 = matrix[:]. This creates a name matrix2 that points to a new list containing all the values of the name matrix
You could use the copy module in the standard library:
from copy import deepcopy
matrix = [[1,2,3],[4,5,6],[7,8,9]]
matrix2 = deepcopy(matrix)
matrix2.remove(matrix2[0])
matrix
[Out]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2
[Out]: [[4, 5, 6], [7, 8, 9]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With