0

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 ?

2
  • 1
    For more background, check out Facts and myths about Python names and values by Ned Batchelder. § "Fact: Python passes function arguments by assigning to them" is especially relevant. Commented May 13, 2024 at 22:40
  • 1
    No automatic copies in Python, not even when things are passed into functions. In the A+= case it is modified in-place, and the changes appear inside and outside the function call. In A= 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. Commented May 14, 2024 at 0:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.