I am getting baffled by how copying a Numpy array works in Python. I start with the following:
import numpy as np
p = np.array([1.0, 0.0, 1.0, 0.3])
Then I try to make "copies" of p using the following three methods:
q = p
q1 = p[:]
q2 = p.copy()
Now I execute q1[2] = 0.2
, and then check the values of q, q1, and q2. I was surprised to find that p, q, and q1 all changed to array([1.0, 0.0, 0.2, 0.3])
, while only q2 remains invariant. I have also used id()
to check the address of all four variables (p, q, q1, q2), and have confirmed that id(p) = id(q)
, but id(q1) != id(p)
.
My question is, if id(q1) != id(p)
, how can a modification of q1 alters p and q? Thanks!