I'm trying to reduce the amount of copying in my code and I came across surprising behavior when dealing with numpy array slicing and views, as explained in:
Scipy wiki page on copying numpy arrays
I've stumbled across the following behavior, which is unexpected for me:
Case 1.:
import numpy as np
a = np.ones((3,3))
b = a[:,1:2]
b += 5
print a
print b.base is a
As expected, this outputs:
array([[ 1., 6., 1.],
[ 1., 6., 1.],
[ 1., 6., 1.]])
True
Case 2: When performing the slicing and addition in one line, things look different:
import numpy as np
a = np.ones((3,3))
b = a[:,1:2] + 5
print a
print b.base is a
The part that's surprising to me is that a[:,1:2] does not seem to create a view, which is then used as a left hand side argument, so, this outputs:
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
False
Maybe someone can shed some light on why these two cases are different, I think I'm missing something.
Solution: I missed the obvious fact that the "+" operator, other than the in-place operator "+=" will always create a copy, so it's in fact not related but slicing other than how in-place operators are defined for numpy arrays.
To illustrate this, the following generates the same output as Case 2:
import numpy as np
a = np.ones((3,3))
b = a[:,1:2]
b = b + 5
print a
print b.base is a
+that creates a new array.