next up previous
Next: Counting vector elements with Up: A sampling of useful Previous: A sampling of useful

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.

Python lists behave the same way. To make a copy of a Python list, you should use b = list(a), rather than b = a. The latter simply gives the same data a second name.



Carleton DeTar 2018-02-12