I wanna create some array in python of array of specified dimension of specific type initialized with same value. i can use numpy arrays of specific size but I am not sure how to initialize them with a specific value. Off course I don’t want to use zeros() or ones()
Thanks a lot.
There are lots of ways to do this. The first one-liner that occurred to me is
tile:You can tile a value in any shape:
However, as a number of answers below indicate, this isn’t the fastest method. It’s designed for tiling arrays of any size, not just single values, so if you really just want to fill an array with a single value, then it’s much faster to allocate the array first, and then use slice assignment:
According to a few tests I did, there aren’t any faster approaches. However, two of the approaches mentioned in answers below are equally fast:
ndarray.fillandnumpy.full.These tests were all done in
ipython, using Python 3.6.1 on a newish mac running OS 10.12.6. Definitions:tileis indeed quite slow:Slice assignment ties with
ndarray.fillandnumpy.fullfor first place:In-place broadcasted addition is only slightly slower:
And non-in-place broadcasted addition is only slightly slower than that: