NumPy array initialization (fill with identical values)
Asked 07 September, 2021
Viewed 1.9K times
  • 56
Votes

I need to create a NumPy array of length n, each element of which is v.

Is there anything better than:

a = empty(n)
for i in range(n):
    a[i] = v

I know zeros and ones would work for v = 0, 1. I could use v * ones(n), but it won't work when v is None, and also would be much slower.

7 Answer