Reputation: 1599
I have an array a
defined outside a for-loop. b
is a variable assigned to be equal to a
inside the loop. I change the values of b
inside the loop which also alters a
. Why/How does this happen?
>>> import numpy as np
>>> a = np.asarray(range(10))
>>> for i in range(5,7):
b = a #assign b to be equal to a
b[b<i]=0 #alter b
b[b>=i]=1
print a
Output:
[0 0 0 0 0 1 1 1 1 1] #Unexpected!!
[0 0 0 0 0 0 0 0 0 0]
Why is a
altered when I don't explicitly do so?
Upvotes: 1
Views: 85
Reputation: 21466
numpy.asarray
is mutable so, a
and b
pointed one location.
>>> a = [1,2,3]
>>> b = a
>>> id(a)
140435835060736
>>> id(b)
140435835060736
You can fix like this b = a[:]
or b = copy.deepcopy(a)
id
returns the “identity” of an object.
Upvotes: 2
Reputation: 95978
Use the slice operator to make a copy. =
just gives it another name as it copies references.
b = a[:]
Will work fine.
According to @AshwiniChaudhary's comment, this won't work for Numpy arrays, the solution in this case is to
b = copy.deepcopy(a)
Upvotes: 1
Reputation: 44385
Because when you do b = a
only the reference gets copied. Both a
and b
point to the same object.
If you really want to create a copy of a
you need to do for example:
import copy
...
b = copy.deepcopy(a)
Upvotes: 2