Reputation: 13
How can I write a function that works like array.append() for numpy.array?
I have tried this
import numpy as np
def append_np(ar, el):
ar = np.append(ar, el)
z = np.array([5], dtype='int32')
z = np.append(z, 6)
append_np(z, 7)
print z
but this code appends only '6':
[5 6]
Upvotes: 0
Views: 809
Reputation: 35761
"that works like array.append()"
First of all, the data structure in Python you most likely are referring to here as "array" is called "list".
Then, the append()
methods for Python lists and Numpy arrays behave fundamentally different. Say that l
is a Python list. l.append()
modifies the list in-place and returns None
. In contrast, Numpy's append()
method for arrays does not change the array it operates on. It returns a new array object.
See: http://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html
A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled.
This explains why you need to return the result of your append_np()
function and assign the return value, as in new_z = append_np(z, 7)
.
You have probably used this function for a Python list:
def append(ar, el):
ar = ar.append(el)
and called it like this:
z = [1, 2]
append(z, 7)
print z
And you have seen that it has modified your z
, indeed. But why, what has happened in this function? The object that was passed as first argument (bound to the name ar
) got modified in-place. That is why z
"on the outside" changed. You made use of this side effect of the function without knowing, and this is dangerous. Within the function the name ar
got re-assigned to the None
singleton object (which is the return value of the list append method). You did not return this object or use it, so this assignment served no purpose in your program. You discovered yourself that this approach is problematic, because when you re-structured your function to append_np()
you suddenly realized that it did not have a "side effect" on z
.
That is, for Python lists you would not outsource the append operation into another function. You would just, from the very beginning, state:
z = [1, 2]
z.append(7)
print z
Upvotes: 3