The following behavior is expected and is what I get. This is consistent with how aliasing works for native Python objects like lists.
>>> x = np.array([1, 2, 3])
>>> y = x
>>> x
array([1, 2, 3])
>>> y
array([1, 2, 3])
>>> x = x + np.array([2, 3, 4])
>>> x
array([3, 5, 7])
>>> y
array([1, 2, 3])
But the following behavior is unexpected by changing x = x + np.array([2, 3, 4])
to x += np.array([2, 3, 4])
>>> x += np.array([2, 3, 4])
>>> x
array([3, 5, 7])
>>> y
array([3, 5, 7])
The Numpy version is 1.16.4 on my machine. Is this a bug or feature? If it is a feature how x = x + np.array([2, 3, 4])
differs from x += np.array([2, 3, 4])
Your line y = x
doesn't create a copy of the array; it simply tells y
to point to the same data as x
, which you can see if you look at their id
s:
x = np.array([1,2,3])
y = x
print(id(x), id(y))
(140644627505280, 140644627505280)
x = x + np.array([2, 3, 4])
will do a reassignment of x to a new id
, while x += np.array([2, 3, 4])
will modify it in place. Thus, the +=
will also modify y, while x = x +...
won't.
x += np.array([2, 3, 4])
print(id(x))
print(x, y)
x = x + np.array([2, 3, 4])
print(id(x))
print(x, y)
140644627505280
[3 5 7] [3 5 7]
140644627175744
[ 5 8 11] [3 5 7]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.