[Numpy-discussion] Initializing an array to a constant value

Pierre Haessig pierre.haessig@crans....
Mon Feb 13 07:30:04 CST 2012

I have a pretty silly question about initializing an array a to a given 
scalar value, say A.

Most of the time I use a=np.ones(shape)*A which seems the most 
widespread idiom, but I got recently interested in getting some 
performance improvement.

I tried a=np.zeros(shape)+A, based on broadcasting but it seems to be 
equivalent in terms of speed.

Now, the fastest :
a = np.empty(shape)

but it is a two-steps instruction to do one thing, which I feel doesn't 
look very nice.

Did I miss an all-in-one function like numpy.fill(shape, A) ?


More information about the NumPy-Discussion mailing list