0
0
NumPydata~5 mins

Why broadcasting matters in NumPy

Choose your learning style9 modes available
Introduction

Broadcasting lets us do math on arrays of different sizes easily. It saves time and makes code simple.

Adding a single number to every element in a list of numbers.
Multiplying each row of a table by a different number without writing loops.
Comparing two lists of different lengths element-wise.
Applying a formula to a matrix and a vector without extra steps.
Syntax
NumPy
result = array1 + array2

Arrays must be compatible in shape for broadcasting to work.

Smaller array is 'stretched' to match the bigger one without copying data.

Examples
Add a single number to each element of an array.
NumPy
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = 5
result = arr1 + arr2
print(result)
Add a 1D array to each row of a 2D array.
NumPy
import numpy as np

arr1 = np.array([[1, 2, 3], [4, 5, 6]])
arr2 = np.array([10, 20, 30])
result = arr1 + arr2
print(result)
Sample Program

This example shows how broadcasting adds a 1D array to each row of a 2D array without loops.

NumPy
import numpy as np

# Create a 2D array (2 rows, 3 columns)
matrix = np.array([[1, 2, 3], [4, 5, 6]])

# Create a 1D array with 3 elements
vector = np.array([10, 20, 30])

# Add vector to each row of matrix using broadcasting
result = matrix + vector

print("Matrix:\n", matrix)
print("Vector:\n", vector)
print("Result of broadcasting addition:\n", result)
OutputSuccess
Important Notes

Broadcasting works only if array shapes are compatible from the right side.

It avoids slow loops and extra memory use.

Understanding broadcasting helps write faster and cleaner code.

Summary

Broadcasting lets you do math on arrays of different shapes easily.

It saves time by avoiding loops and extra memory.

It is a key feature to learn for efficient data science with numpy.