2

The goal is to update a list by function call which takes two arguments, one being the list to be modified. In the following example, j is the list to be modified by function f():

import numpy as np

j = np.log(np.array([[0.3],[0.4]]))
k = np.log(np.array([[0.1],[0.3]]))

def f(a,b):
    a = np.exp(a) - np.exp(b)

f(j,k)

print(j)

The expected solution was:

[[ 0.2]
 [ 0.1]]

However, it produces :

[[-1.2039728 ]
 [-0.91629073]]

which is the original value of j. That is, j was never modified.

But if the += is used instead with the -a trick,

def f(a,b):
    a += -a + np.exp(a) - np.exp(b)

then the output is the expected solution.

Hence, the question: does the assignment operator overwrite argument reference in Python functions? Is there an explanation for why j's behavior changes if = or += is used?

  • 2
    Yes. `a = ` *never directly modifies `a`, it merely changes the object that the variable `a` is referencing*. Augmented assignment *may* change an object in-place, which happens to be true for `numpy` arrays, but not, for example, with `int` objects (since they are immutable). Please read the following: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Dec 11 '17 at 21:33
  • 1
    Also, python does not support pass-by-reference semantics at all. – juanpa.arrivillaga Dec 11 '17 at 21:35

0 Answers0