The numpy.full() function returns a new ndarray of specified shape and data type, filled entirely with a chosen scalar value.
Arbitrary Sentinel & Constant Initialization: Unlike specialized constructors that produce only zeros or ones, np.full() populates arrays with any arbitrary scalar value, including integers, floating-point sentinels (np.nan, np.inf), or custom strings. Define dimensions with shape tuples, enforce precision with dtype, or mirror existing arrays with numpy.full_like(). For zero- or one-filled arrays, see numpy.zeros() and numpy.ones().
The numpy.full() function accepts array dimensions, fill value, and optional parameters:
# Formal syntax of numpy.full()
numpy.full(shape, fill_value, dtype=None, order='C', *, like=None)
| Parameter | Type | Default | Description & Operational Rule |
|---|---|---|---|
shape |
int or tuple of ints |
Required | Shape of the new array (e.g., 4 for 1D, (3, 4) for 2D). |
fill_value |
scalar | Required | Scalar constant used to populate every element of the array. |
dtype |
data-type | None |
Desired data type. If omitted, inferred from the fill_value type. |
order |
{'C', 'F'} |
'C' |
Memory layout in RAM: 'C' (row-major) or 'F' (column-major). |
| Return | ndarray |
N/A | Constant-filled array with the specified shape, value, and dtype. |
Passing an integer creates a 1D vector; passing a tuple defines multi-dimensional coordinate axes:
# 1. 1D vector and 2D matrix filled with custom scalar
import numpy as np
# 1D vector filled with 7
vec = np.full(4, 7)
print("1D Vector (7): ", vec)
print("Dtype: ", vec.dtype)
# 2D matrix filled with 3.14
mat = np.full((3, 3), 3.14)
print("\n2D Matrix (3x3 with 3.14):\n", mat)Terminal Output:
1D Vector (7): [7 7 7 7]
Dtype: int64
2D Matrix (3x3 with 3.14):
[[3.14 3.14 3.14]
[3.14 3.14 3.14]
[3.14 3.14 3.14]]
In data science pipelines, arrays frequently need initialization with sentinel flags like np.nan or np.inf:
# 2. Filling with Sentinel Values: NaN and Infs
import numpy as np
nan_grid = np.full((2, 3), np.nan)
inf_grid = np.full((2, 3), np.inf)
print("NaN Matrix:\n", nan_grid)
print("\nInf Matrix:\n", inf_grid)Terminal Output:
NaN Matrix:
[[nan nan nan]
[nan nan nan]]
Inf Matrix:
[[inf inf inf]
[inf inf inf]]
By default, dtype is inferred from the fill_value. You can override and coerce types explicitly:
# 3. Specifying dtypes and casting fill_values
import numpy as np
# Integer 42 coerced to float64
f_arr = np.full(3, 42, dtype=float)
# String fill value
s_arr = np.full((2, 2), 'alpha', dtype='<U6')
print("Float-cast array: ", f_arr)
print("String array: \n", s_arr)Terminal Output:
Float-cast array: [42. 42. 42.]
String array:
[['alpha' 'alpha']
['alpha' 'alpha']]
The order parameter specifies row-major ('C') or column-major ('F') physical memory layout:
# 4. Storage layout: Row-Major ('C') vs. Column-Major ('F')
import numpy as np
c_arr = np.full((3, 3), 9, order='C')
f_arr = np.full((3, 3), 9, order='F')
print("C-contiguous (row-major): ", c_arr.flags['C_CONTIGUOUS'])
print("F-contiguous (column-major):", f_arr.flags['F_CONTIGUOUS'])Terminal Output:
C-contiguous (row-major): True
F-contiguous (column-major): True
Use numpy.full_like() to allocate an array mirroring an existing array's shape and dtype:
# 5. Mirroring prototype arrays with numpy.full_like()
import numpy as np
prototype = np.zeros((2, 4), dtype=np.int32)
filled = np.full_like(prototype, fill_value=99)
print("Prototype shape & dtype:", prototype.shape, prototype.dtype)
print("Mirrored full array: \n", filled)Terminal Output:
Prototype shape & dtype: (2, 4) int32
Mirrored full array:
[[99 99 99 99]
[99 99 99 99]]
NumPy provides specialized constructors depending on your initialization needs:
| Function | Initial Contents | Speed | When to Use |
|---|---|---|---|
np.full() |
Arbitrary scalar fill value | Fast | Sentinel constants (e.g. -1 or NaN). |
np.zeros() |
All zeros (0.0 or 0) |
Fast | Accumulators, image masks, zero padding. |
np.ones() |
All ones (1.0 or 1) |
Fast | Unit weights, normalization bases, scaling. |
np.empty() |
Uninitialized memory | Fastest | Arrays immediately overwritten in loops. |
Initializing a shortest-path distance matrix with infinity:
# 6. Production Recipe: Baseline Game Grid / Distance Matrix Initializer
import numpy as np
# Initializing a 5x5 shortest-path cost matrix with infinity
cost_matrix = np.full((5, 5), fill_value=np.inf)
np.fill_diagonal(cost_matrix, 0.0)
print("Initial cost matrix:\n", cost_matrix)Terminal Output:
Initial cost matrix:
[[ 0. inf inf inf inf]
[inf 0. inf inf inf]
[inf inf 0. inf inf]
[inf inf inf 0. inf]
[inf inf inf inf 0.]]Creating a constant-value boundary canvas buffer:
# 7. Production Recipe: Constant Value Boundary Padding
import numpy as np
# Creating an image border canvas filled with neutral gray (128)
gray_canvas = np.full((100, 100), fill_value=128, dtype=np.uint8)
gray_canvas[10:90, 10:90] = 255 # Inner white patch
print("Canvas shape: ", gray_canvas.shape)
print("Boundary pixel: ", gray_canvas[0, 0])
print("Inner patch pixel:", gray_canvas[50, 50])Terminal Output:
Canvas shape: (100, 100)
Boundary pixel: 128
Inner patch pixel: 255
Watch for dtype truncation when passing float fill values to integer arrays:
# 8. Common traps: Fill value type truncation
import numpy as np
# Trap: Float truncated to int when dtype=int is specified
int_truncated = np.full(3, 3.85, dtype=int)
print("Truncated float: ", int_truncated) # Values are 3, not 3.85!
# Shape tuple trap
try:
np.full(3, 3, 5) # 3 positional args interpreted incorrectly
except TypeError as err:
print("Caught TypeError:", err)Terminal Output:
Truncated float: [3 3 3]
Caught TypeError: 'int' object cannot be interpreted as an integer
Practice constant array creation and buffer allocation in our companion notebook:
Run interactive cells, experiment with sentinel values, benchmark memory order, and run assertions.
View on GitHub Run in Google ColabRun unit assertions to verify numpy.full() mechanics:
# 9. Self-verifying unit test suite for numpy.full()
import numpy as np
# Test 1: 1D vector shape and fill value
v = np.full(5, 42)
assert v.shape == (5,) and np.all(v == 42)
# Test 2: Float NaN matrix
nan_m = np.full((3, 3), np.nan)
assert nan_m.shape == (3, 3) and np.all(np.isnan(nan_m))
# Test 3: full_like equivalence
proto = np.zeros((2, 4), dtype=np.int16)
f_like = np.full_like(proto, 7)
assert f_like.shape == (2, 4) and f_like.dtype == np.int16 and np.all(f_like == 7)
print("All numpy.full() unit assertions successfully verified!")Terminal Output:
All numpy.full() unit assertions successfully verified!
If dtype=None, NumPy infers it from type(fill_value).
Yes, np.full(shape, np.nan) creates an array of float NaNs.
np.zeros() only produces zeros; np.full() accepts any constant scalar.
Use np.full_like(arr, val) to copy shape and dtype automatically.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.