The following produces two different behaviors
import numpy as np
def func1 (A, B):
A = A * B
return A
def func2 (A, B):
A *= B
return A
A = np.arange(3, dtype=float)
B = np.full( 3, 2.0 )
C1 = func1 (A, B)
print ( " func 1", C1)
print ( " A after function 1 = ", A)
print ()
The result is as expected C1 = [0.0, 2.0, 4.0] and A is unchanged, still [0.0, 1.0, 2.0]
Repeating above with func2
A = np.arange(3, dtype=float)
B = np.full(3, 2.0 )
C2 = func2 (A, B)
print (" func 2", C2)
print (" A after function 2 = ", A)
The result is as expected for C2 = [0.0, 2.0, 4.0] but A is changed, [0.0, 2.0, 4.0]
This is rather dangerous, as I thought the array A inside func2 will be a copy as soon as it's used for calculation such as above. Can anyone explain why such behavior ? Shouldn't they be expected to be same ?
A+=case it is modified in-place, and the changes appear inside and outside the function call. InA=a new array is created inside the function, and links to the outside variable are broken. No copying in either case. So several things are going on here.