Copying arrays

In the example below

>>> a = np.array([1,2,3])
>>> b = a

you might think that b = a makes a new copy of the array. It doesn't. Instead, the variable b becomes another name for the data referred to by a. So if you change b, you end up making the same change to a.

>>> b[1] = -1
>>> print(b)
[ 1 -1  3]
>>> print(a)
[ 1 -1  3]

Usually we really want to make a new copy. To do that numpy provides a copy function np.copy():

>>> a = np.array([1,2,3])
>>> b = np.copy(a)
>>> b[1] = -1
>>> print(b)
[ 1 -1  3]
>>> print(a)
[1 2 3]

In this case changing b does not also change a. This what we usually want.