NumPy
Broadcasting
Combine arrays of compatible shapes without copying.
By EZ4Code Team
broadcastingshapes
Code
import numpy as np
# Add scalar to every element
a = np.array([1, 2, 3])
print(a + 10)
# Add row vector to every row of a matrix
matrix = np.ones((3, 4))
row = np.array([1, 2, 3, 4])
print(matrix + row)
# Normalize columns: subtract mean, divide by std
data = np.random.rand(5, 3)
mean = data.mean(axis=0)
std = data.std(axis=0)
normalized = (data - mean) / std
# Outer product via broadcasting
outer = np.arange(3).reshape(3, 1) * np.arange(4).reshape(1, 4)Explanation
Broadcasting stretches smaller arrays to match a larger one without copying data, so arithmetic just works when trailing dimensions align or are 1. A scalar broadcasts against any array, and a row vector broadcasts against every row of a matrix. This pattern keeps normalization and outer-product code both short and fast.
More NumPy Snippets
Array Creation
Create arrays from lists and built-in constructors.
Indexing and Slicing
Slice arrays and index with boolean masks.
Math Operations
Apply element-wise math and reductions.
Linear Algebra
Solve systems, factorize, and compute eigenvalues.
Random Numbers
Sample from distributions with a Generator.
Reshaping
Reshape, transpose, and stack arrays.