pythonnumpyvariablesvariable-assignmentassignment-operator

I can't assign my desired value to a variable properly in python


I wanna manipulate the matrix "b", but since I've assigned its initial value equal to initial value of matrix "a", the matrix "a" is also gets manipulated which is not desired. How can I solve this problem?

import numpy as np
a=np.zeros((3,3))
b=a
b[0,:]=1
print('a=',a,'\n')

print('b=',b)

And the result of this code is this:

a= [[1. 1. 1.]
 [0. 0. 0.]
 [0. 0. 0.]] 

b= [[1. 1. 1.]
 [0. 0. 0.]
 [0. 0. 0.]]

As you see both of these matrices have been modified. I wrote this little code to illustrate my problem. My main program is a bigger one but I've recognized the issue and this is it.


Solution

  • Since arrays a & b are both mutable objects in python, a simple = makes them point to the same location in memory -- hence, a change to a results in a change to b as well. This is called a shallow copy.

    What you are looking for is a deep copy:

    b = a.copy()

    See this tutorial for more details on shallow vs deep copies, or this one.

    Built-in types like int, float, etc. are immutable objects in python, so there is no shallow copy.