Unexpected behavior for numpy self division

def f(x): x=x/5. return x def g(x): x/=5. return x

x_var = np.arange(5,dtype=np.double)
print x_var
print x_var

[ 0.  1.  2.  3.  4.]
[ 0.   0.2  0.4  0.6  0.8]

This behavior is a little bit strange to me, I always thought x/=5. was equivalent to x=x/5. . But clearly the g(x) function does not create a new reference with /= operation. Could anyone offer an explanation for this?

Best answer

I always thought x/=5. was equivalent to x=x/5

It is, unless the class overrides the __idiv__ operator, like numpy.ndarray does.
numpy.ndarray overrides it to modify the array in-place, which is good because it avoids creating a new copy of the array, when copying is not required. As you can guess, it also overrides the rest of the __i*__ operators.