[Numpy-discussion] strange behaviour with numpy arrays
Julian Taylor
jtaylor.debian at googlemail.com
Wed Sep 11 06:40:32 EDT 2013
On 11.09.2013 12:33, antlarac wrote:
> Hi, I have a numpy array, and I want to create another variable equal to it,
> to back it up for later calculations, because the first array will change.
> But after the first array changes, the second automatically changes to the
> same value. An example of what happens:
>
> import numpy as np
> a=np.zeros((4,4))
> b=a
> print(b)
> a[3,3]=3
> print(' ')
> print(b)
>
> gives the result:
>
> [[ 0. 0. 0. 0.]
> [ 0. 0. 0. 0.]
> [ 0. 0. 0. 0.]
> [ 0. 0. 0. 0.]]
>
> [[ 0. 0. 0. 0.]
> [ 0. 0. 0. 0.]
> [ 0. 0. 0. 0.]
> [ 0. 0. 0. 3.]]
>
> As you can see, when the value of a changes, the value of b automatically
> changes, even when this is not asked. Is there a way of avoiding this?
>
> This problem does not happen with normal python variables.
> Thank you for your time.
>
this is normal, python tracks its mutable variables as references.
b=a
makes b a reference to a so changing a changes b too.
python lists work the same way:
In [1]: a = [1,2,3]
In [2]: b = a
In [3]: b[2] = 9
In [4]: b
Out[4]: [1, 2, 9]
In [5]: a
Out[5]: [1, 2, 9]
note that python integers and strings a not mutable, so it does not
behave the same way.
to avoid it make explicit copies.
b = a.copy()
Also note that slices of array (a[:5]) in numpy are *not* copies but
views on the original array.
This is different than python list slices which are shallow copies.
More information about the NumPy-Discussion
mailing list