3

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

Kavan
  • 331
  • 1
  • 4
  • 13
  • you need to make a deep copy of your matrix ... possible duplicate of http://stackoverflow.com/questions/6431973/how-to-copy-data-from-a-numpy-array-to-another – Julien Spronck Feb 16 '16 at 09:50
  • Nope @JulienSpronck. My question is "What is happening here!!??" I am removing row of matrix2, why row from matrix is also removed!? – Kavan Feb 16 '16 at 09:52
  • check this other question as well ... http://stackoverflow.com/questions/17246693/what-exactly-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignm – Julien Spronck Feb 16 '16 at 09:58

3 Answers3

5

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

donkopotamus
  • 22,114
  • 2
  • 48
  • 60
3

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]]
meltdown90
  • 251
  • 1
  • 11
2

List is mutable type, when you assign it with assignment operator to a different variable (matrix2=matrix), it just refer the same object, means two reference variable (matrix2,matrix) refers the same object. so in this case we need to copy the actual object by using copy.copy() or copy.deepcopy(), function and assign to the other variable. here I am using copy.copy().

from copy import *

matrix = [[1,2,3],[4,5,6],[7,8,9]] 
matrix1 = copy(matrix)    
matrix1.remove(matrix1[0])

matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] 
matrix1 
[[4, 5, 6], [7, 8, 9]]
Vikram Singh Chandel
  • 1,290
  • 2
  • 17
  • 36