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

eat e.antero.tammi at gmail.com
Mon Feb 13 13:17:55 EST 2012


Hi,

A slightly OT (and not directly answering to your question), but

On Mon, Feb 13, 2012 at 3:30 PM, Pierre Haessig <pierre.haessig at crans.org>wrote:

> 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)
> a.fill(A)
>
wouldn't it be nice if you could just write:
a= np.empty(shape).fill(A)
this would be possible if .fill(.) just returned self.

I assume that this topic has been discussed previously, but personally I
feel that the code would be more readable when returning self rather None.
Thus all ndarray methods should return something meaningful to act on (in
the spirit that methods are more like functions than subroutines).


Just my 2 cents,
-eat

>
> 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) ?
>
> Best,
> Pierre
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20120213/562949eb/attachment.html>


More information about the NumPy-Discussion mailing list