np.full(shape, value) directly allocates an array of the requested shape and fills every element with value, inferring the array's dtype from the fill value unless one is given explicitly. It's the most direct way to create an array pre-filled with any constant, more explicit than the common but slightly indirect pattern of multiplying an np.ones() array by that value, and unlike that pattern, it works cleanly even for values, like strings or specific dtypes, where multiplying wouldn't make sense.
1Understanding np.full()
np.full(shape, value) directly allocates an array of the requested shape and fills every element with value, inferring the array's dtype from the fill value unless one is given explicitly. It's the most direct way to create an array pre-filled with any constant, more explicit than the common but slightly indirect pattern of multiplying an np.ones() array by that value, and unlike that pattern, it works cleanly even for values, like strings or specific dtypes, where multiplying wouldn't make sense.
Use np.full_like(other_array, value) instead of np.full(other_array.shape, value) when you want a filled array matching another array's shape and dtype exactly, without repeating that information manually.
import numpy as np
arr = np.full((2, 3), 7)
print(arr)2Practical Example
Here is a real-world application of np.full() showing how it is used in production NumPy code.
import numpy as np
template = np.zeros((2, 2))
filled = np.full_like(template, -1)
print(filled)3Best Practices
Follow these guidelines when working with np.full():
1. Use np.full(shape, value) directly instead of np.ones(shape) times value for filling an array with any constant other than 0 or 1
2. Specify dtype explicitly when the value's inferred type doesn't match what you actually need for the resulting array
3. Use np.full_like() when you want a filled array that matches an existing array's shape and dtype, rather than manually reading and passing its shape and dtype yourself
Tip: Use np.full_like(other_array, value) instead of np.full(other_array.shape, value) when you want a filled array matching another array's shape and dtype exactly, without repeating that information manually.
import numpy as np
arr = np.full((2, 3), 7)
print(arr)