Reputation: 2034
Here is minimal code:
A = np.zeros((2,2))
B = A
A[0,0] = 2
print A
print B
which outputs:
[[ 2. 0.]
[ 0. 0.]]
[[ 2. 0.]
[ 0. 0.]]
I expected B
to stay them same, but instead it's updated to the new value of A
? What are the mechanics behind this and what's the general rule to know why/when this would happen? It seems kind of dangerous...
Upvotes: 3
Views: 3682
Reputation: 86
This is in general python behaviour and not specific to numpy. If you have an object such as list
you will see a similar behaviour.
a = [1]
b = a
b[0] = 7
print a
print b
will output
[7]
[7]
This happens because variable a is pointing to a memory location where the array [1] is sitting and then you make b point to the same location. So if the value at that location changes, both the variables are still pointing there. If you want to get around this behaviour you'll need to use the .copy() function like this.
A = np.zeros((2,2))
B = A.copy()
A[0,0] = 2
print A
print B
which outputs..
[[2. 0.]
[0. 0.]]
[[0. 0.]
[0. 0.]]
Using the copy() function will spawn a whole new object instead of pointing to the old one. Caution: This may not be the ideal way to do it since copying a huge numpy array can be computationally expensive
EDIT: Removed the word mutable since the behaviour is also applicable to immutables.
Upvotes: 3