np.ones() works identically to np.zeros(), but fills every element with 1 instead of 0. It's commonly used to initialize weights or bias terms in simple numerical models, to build a mask that starts as 'everything included' before selectively zeroing entries out, or combined with scalar multiplication to build an array pre-filled with a constant other than 0 or 1, though np.full() is the more direct way to do that.
1Understanding np.ones()
np.ones() works identically to np.zeros(), but fills every element with 1 instead of 0. It's commonly used to initialize weights or bias terms in simple numerical models, to build a mask that starts as 'everything included' before selectively zeroing entries out, or combined with scalar multiplication to build an array pre-filled with a constant other than 0 or 1, though np.full() is the more direct way to do that.
Multiplying np.ones(shape) by a scalar is a common but slightly indirect way to fill an array with a constant value — np.full(shape, value) expresses the same intent more directly and without the extra multiplication.
import numpy as np
arr = np.ones(4)
print(arr)2Practical Example
Here is a real-world application of np.ones() showing how it is used in production NumPy code.
import numpy as np
mask = np.ones((3, 3), dtype=bool)
mask[1, 1] = False
print(mask)3Best Practices
Follow these guidelines when working with np.ones():
1. Use np.ones() to initialize arrays that need an all-true or all-included starting state, like a mask before selectively disabling entries
2. Prefer np.full(shape, value) over np.ones(shape) times value when the fill value isn't literally 1
3. Specify dtype explicitly when the array represents something other than floating-point weights, like a boolean or integer mask
Tip: Multiplying np.ones(shape) by a scalar is a common but slightly indirect way to fill an array with a constant value — np.full(shape, value) expresses the same intent more directly and without the extra multiplication.
import numpy as np
arr = np.ones(4)
print(arr)