max - 1 year ago 92

Python Question

I need to create a NumPy array of length

`n`

`v`

Is there anything better than:

`a = empty(n)`

for i in range(n):

a[i] = v

I know

`zeros`

`ones`

`v * ones(n)`

`v`

`None`

Answer Source

NumPy 1.8 introduced `np.full()`

, which is a more direct method than `empty()`

followed by `fill()`

for creating an array filled with a certain value:

```
>>> np.full((3, 5), 7)
array([[ 7., 7., 7., 7., 7.],
[ 7., 7., 7., 7., 7.],
[ 7., 7., 7., 7., 7.]])
>>> np.full((3, 5), 7, dtype=int)
array([[7, 7, 7, 7, 7],
[7, 7, 7, 7, 7],
[7, 7, 7, 7, 7]])
```

This is arguably *the* way of creating an array filled with certain values, because it explicitly describes what is being achieved (and it can in principle be very efficient since it performs a very specific task).