Search code examples
pythonarraysnumpycall

Manipulate values of global arrays within functions


Please consider the following two examples. Example 1:

def f(inp):
    inp[0] = 42
    inp.append(12)
    inp.append(13)

v = [1, 2, 3, 4]
f(v)
print(v)

>>> [42, 2, 3, 4, 12, 13]

And here goes example 2:

def g(inp):
    inp[0] = 42
    np.append(inp, [12, 13])

u = np.array([1, 2, 3, 4])
g(u)
print(u)

>>> [42  2  3  4]

In the first one, the function can change elements of the global list and append to it. This is because Python calls functions by reference. But why can the second function change a value of a global ndarray, but can not append to it?


Solution

  • http://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html:

    arr: Values are appended to a copy of this array.

    so you're modifying a copy that is local in g()