clean way prepend an element to a numpy array

bdb112 boyd.blackwell at gmail.com
Mon Jul 20 23:56:51 EDT 2009


If I want to add an element at the beginning of an array, it seems
like I must make a list, insert in place, then make an array again.

Of course, lists can be efficient too, and the insert() funtion works
nicely in that case, but sometimes arrays are the best choice

e.g.
x=array([1,2,3])
# to put the element 0 at the head of the array
listx=list(x)
listx.insert(0,0)
x=array(listx)
# this extra effort distracts from the clarity of the code, and must
slow things a little.

# While I appreciate that array operations that cause memory re-
allocation and copying are to be
#  avoided if at all possible, sometimes this is the best compromise
between clarity and efficiency

# A nicer piece of code would be

x.insert(0,0)
#or
x.prepend(0)

# It is a little easier to grow an array at the end (if it is not
referenced)
x.resize(4)

I saw this interest syntax on this site
x[:0]=0

I guess that is cute, but could be confusing....(and doesn't work)



More information about the Python-list mailing list