We use np.broadcast_to() to stretch a smaller array to a bigger shape without copying data. This helps when you want to do math with arrays of different sizes.
0
0
np.broadcast_to() for explicit broadcasting in NumPy
Introduction
You have a small array and want to match the shape of a bigger array for calculations.
You want to repeat data logically without making a full copy in memory.
You need to prepare arrays for element-wise operations in machine learning.
You want to avoid writing loops by using array broadcasting explicitly.
You want to understand how NumPy handles arrays of different shapes.
Syntax
NumPy
np.broadcast_to(array, shape, subok=False)array is the input array you want to broadcast.
shape is the new shape you want to broadcast to. It must be compatible.
Examples
This repeats the 1D array
x into a 3x3 array by broadcasting.NumPy
import numpy as np x = np.array([1, 2, 3]) y = np.broadcast_to(x, (3, 3)) print(y)
Broadcast a 3x1 array to 3x4 by repeating the single column.
NumPy
a = np.array([[1], [2], [3]]) b = np.broadcast_to(a, (3, 4)) print(b)
Sample Program
This code shows how a 1D array of length 2 is broadcasted to a 3x2 array. The values are repeated logically without copying.
NumPy
import numpy as np # Original small array arr = np.array([10, 20]) # Broadcast to a bigger shape broadcasted_arr = np.broadcast_to(arr, (3, 2)) print("Original array shape:", arr.shape) print("Broadcasted array shape:", broadcasted_arr.shape) print("Broadcasted array:") print(broadcasted_arr)
OutputSuccess
Important Notes
The new shape must be compatible with the original array shape, or you get an error.
np.broadcast_to() does not copy data, so it is memory efficient.
Broadcasted arrays are read-only to avoid accidental changes.
Summary
np.broadcast_to() stretches arrays to bigger shapes for easy math.
It repeats data logically without copying, saving memory.
Use it when you want to prepare arrays for element-wise operations.