1

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])

1 Answer 1

2

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 ids:

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]
Sign up to request clarification or add additional context in comments.

1 Comment

The main takeaway from this: whenever you are confused about "aliasing" (as the OP refers to it), make generous use of print(id(x)) to see what is going on, and that typically clears things up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.