0
0
NumPydata~5 mins

np.full() for custom-filled arrays in NumPy

Choose your learning style9 modes available
Introduction

We use np.full() to quickly create arrays filled with the same value. This helps when you want a starting point or a fixed value repeated many times.

When you want an array filled with zeros, ones, or any specific number for calculations.
When you need a placeholder array before filling it with real data.
When testing algorithms that require input arrays with constant values.
When initializing weights or biases in simple machine learning models.
When creating masks or filters with a fixed value.
Syntax
NumPy
import numpy as np

array = np.full(shape, fill_value, dtype=None, order='C')

shape is the size of the array you want, like (3, 4) for 3 rows and 4 columns.

fill_value is the number you want to fill the array with.

Examples
This creates a 2 rows by 3 columns array where every element is 7.
NumPy
import numpy as np

# Create a 2x3 array filled with 7
array = np.full((2, 3), 7)
print(array)
Shows what happens if the shape is empty: the result is an empty array.
NumPy
import numpy as np

# Create an empty array with shape (0,) filled with 5
array = np.full((0,), 5)
print(array)
Creates a single-element array with the value 10.
NumPy
import numpy as np

# Create a 1-element array filled with 10
array = np.full((1,), 10)
print(array)
Creates a 3x3 array filled with 0.5 as floats.
NumPy
import numpy as np

# Create a 3x3 array filled with 0.5 and specify float type
array = np.full((3, 3), 0.5, dtype=float)
print(array)
Sample Program

This program creates a 4 by 5 array filled with 9. Then it changes one element to 0 to show how you can modify the array after creating it.

NumPy
import numpy as np

# Create a 4x5 array filled with 9
array_before = np.full((4, 5), 9)
print("Array before change:")
print(array_before)

# Change the value at position (2,3) to 0
array_before[2, 3] = 0
print("\nArray after changing one element to 0:")
print(array_before)
OutputSuccess
Important Notes

Time complexity is O(n) where n is the total number of elements, because it fills each element.

Space complexity is O(n) because it creates a new array of the given size.

A common mistake is to forget that shape must be a tuple, even for 1D arrays (use (5,) not 5).

Use np.full() when you want a fixed value repeated. Use np.zeros() or np.ones() if you only need zeros or ones.

Summary

np.full() creates arrays filled with the same value.

It needs the shape and the fill value as inputs.

Useful for initializing arrays with constant values for calculations or placeholders.