You can use slice assignment here just like you would a list:
def func(my_array):
my_array[:3] = [1,2,3]
Note that this still requires that my_array
has at least 3 elements in it ... Example usage:
>>> def func(my_array):
... my_array[:3] = [1,2,3]
...
>>> a = np.zeros(4)
>>> a
array([ 0., 0., 0., 0.])
>>> func(a)
>>> a
array([ 1., 2., 3., 0.])
The thing you're missing is how python deals with references. When you enter my_function
, you have a reference to the original ndarray object bound to the name my_array
. However, as soon as you assign something new to that name, you lose your original reference and replace it with a reference to a new object (in this case, a list).
Note that having a default argument which is a mutable object can often lead to surprises