Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying a numpy array inside a function?

I have a problem with the simple program below :

def my_function(my_array = np.zeros(0)):
    my_array = [1, 2, 3]

my_array = np.zeros(0)
my_function(my_array)
print my_array

It prints an empty array as if my_array was passed by copy and not by reference inside the function. How to correct that ?

like image 713
Vincent Avatar asked Nov 28 '22 11:11

Vincent


1 Answers

The pass-by-reference model is more of a pass-by-value of a pointer. So inside your my_function you have a copy of a pointer to your original my_array. If you were to use that pointer to manipulate the inputed array directly that would make a change, but a re-assignment of the copied pointer won't affect the original array.

As an example:

def my_func(a):
    a[1] = 2.0

ar = np.zeros(4)
my_func(ar)
print ar

The above code will change the internal value of ar.

like image 160
Ramón J Romero y Vigil Avatar answered Dec 15 '22 22:12

Ramón J Romero y Vigil