Possible Duplicate:
Variable assignment and modification (in python)
I just noticed that variable assignation in python had some behaviour which I didn’t expect. For example:
import numpy as np
A = np.zeros([1, 3])
B = A
for ind in range(A.shape[1]):
A[:, ind] = ind
B[:, ind] = 2 * ind
print 'A = ', A
print 'B = ', B
outputs
A = [[ 0. 2. 4.]]
B = [[ 0. 2. 4.]]
While I was expecting:
A = [[ 0. 1. 2.]]
B = [[ 0. 2. 4.]]
If I replace “B = A” by “B = np.zeros([1, 3])”, then I have the right thing.
I can’t reproduce the unexpected result in Ipython terminal. I got that result in SciTE 3.1.0 using F5 key to run the code. I’m using Python(x, y) 2.7.2.3 distro in Win7.
In your code,
Bis just another name forA, so when you change one you change the other. This is a common “problem” with mutable objects in Python. With numpy arrays, you can use thecopy()function.However, this also happens with mutable containers, such as lists or dictionaries. To avoid this, you can one of one of these: (depending on the complexity of the mutable)
Note that to use the
copyanddeepcopyfunctions, you need to import them from the standard modulecopy.See also: this question