NumPy array initialization fill with identical values
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
NumPy provides several functions to create arrays pre-filled with a specific value. np.full() is the most direct — it creates an array of a given shape filled with a specified value. Other options include np.zeros(), np.ones(), and np.empty() followed by fill(). The choice depends on the fill value and whether you need control over dtype and memory allocation.
np.full() (Recommended)
np.full() is the clearest way to create a filled array. It accepts any scalar value and infers or accepts a dtype.
np.zeros() and np.ones()
np.empty() + fill()
np.empty() allocates memory without initializing it (faster), then fill() sets all values:
The speed difference is negligible for most use cases. Prefer np.full() for clarity.
Multiplication Trick
_like Functions (Match Existing Array Shape)
np.repeat and np.tile
For creating arrays with repeated patterns:
Performance Comparison
For zero-filled arrays, np.zeros() is fastest because the OS may provide pre-zeroed memory pages. For other values, np.full() is optimal.
Common Pitfalls
- Using
np.empty()without filling:np.empty()does not initialize values — the array contains whatever was in memory. Reading from an unfillednp.empty()array produces garbage values, not zeros. - Unintended dtype from
np.full():np.full((3,3), 7)creates anint64array, butnp.full((3,3), 7.0)createsfloat64. The fill value determines the dtype if not specified explicitly. Always passdtypewhen the type matters. np.zerosreturns floats by default:np.zeros((3,3))createsfloat64, notint. Passdtype=intif you need integers. This catches many people when using zeros as indices or counts.- Modifying shared references:
arr = np.full((3,3), [1,2,3])does not fill with a list — it broadcasts the list across rows. For object arrays with mutable elements, modifications to one element affect all (usedtype=objectcarefully). np.ones() * valuecreates a temporary array: This allocates two arrays (the ones array and the result) instead of one.np.full()is both clearer and more memory-efficient.
Summary
- Use
np.full(shape, value)to fill an array with any value — the recommended approach - Use
np.zeros(shape)for zero-filled arrays andnp.ones(shape)for ones - Use
np.full_like(arr, value)to match an existing array's shape and dtype np.empty()is fastest for allocation but does not initialize values — always fill afterward- Always specify
dtypeexplicitly when the type matters (int vs float) - Avoid
np.ones() * value— it is less efficient and less readable thannp.full()

