0

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]
1
  • What are you trying to do? numpy.append is very inefficient because it copies the whole array each time it appends. If you have to use it a lot, you are probably better off converting to a list then append and when you are done convert back to np.array. Of course if you know the size of your final array, you can pre-allocate memory, e.g. numpy.empty(100000), and then fill in your array. Commented Feb 14, 2015 at 16:01

1 Answer 1

3

"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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.