A numpy array unexpectedly changes when changing another one despite being separate

The issue is that when you’re assigning values back to w1 from w2 you aren’t actually passing the values from w1 to w2, but rather you are actually pointing the two variables at the same object.

The issue you are having

w1 = np.array([1,2,3])
w2 = w1

w2[0] = 3

print(w2)   # [3 2 3]
print(w1)   # [3 2 3]

np.may_share_memory(w2, w1)  # True

The Solution

Instead you will want to copy over the values. There are two common ways of doing this with numpy arrays.

w1 = numpy.copy(w2)
w1[:] = w2[:]

Demonstration

w1 = np.array([1,2,3])
w2 = np.zeros_like(w1)

w2[:] = w1[:]

w2[0] = 3

print(w2)   # [3 2 3]
print(w1)   # [1 2 3]

np.may_share_memory(w2, w1)   # False

Leave a Comment