Why does python/numpy's += mutate the original array?

前端 未结 4 1247
我寻月下人不归
我寻月下人不归 2020-12-02 01:40
import numpy as np

W = np.array([0,1,2])
W1 = W
W1 += np.array([2,3,4])
print W

W = np.array([0,1,2])
W1 = W
W1 = W1 + np.array([2,3,4])
print W

4条回答
  •  执念已碎
    2020-12-02 02:31

    In the case of

    W = np.array([0,1,2])
    W1 = W
    W1 += np.array([2,3,4])
    

    W points to some location in memory, holding a numpy array. W1 points to the same location. W1 += np.array([2,3,4]) takes that location in memory, and changes the contents.

    In this case:

    W = np.array([0,1,2])
    W1 = W
    W1 = W1 + np.array([2,3,4])
    

    W and W1 start out pointing to the same location in memory. You then create a new array (W1 + np.array([2,3,4])) which is in a new location in memory. (Keep in mind: the right hand side is always evaluated first, and only then is it assigned to the variable on the left hand side.) Then, you make W1 point to this new location in memory (by assigning W1 to this new array). W still points to the old location in memory. From this point on, W and W1 are no longer the same array.

提交回复
热议问题