← Back to NumPy Course | Chapter 6: Math Operations | Lesson 2 of 7

Broadcasting basics

Broadcasting lets NumPy stretch a smaller array so it can be combined with a bigger one without copying data.

In this page:

  1. Broadcasting basics
Syntax
python
# shapes are compared from the last axis backwards
result = arr_shape_3_by_1 + arr_shape_1_by_4    # -> shape (3, 4)

Broadcasting basics

When shapes differ, NumPy compares them from the last axis backwards. Dimensions are compatible if they are equal or one of them is 1, and the size-1 axis is stretched. This lets you add a row to every row of a matrix in one expression.

Note: If broadcasting fails you will see a ValueError mentioning operands could not be broadcast together.

Example: Broadcasting basics

python
import numpy as np

m = np.array([[1, 2, 3], [4, 5, 6]])
row = np.array([10, 20, 30])
col = np.array([[100], [200]])
print(m + row)
print(m + col)

# Output:
# [[11 22 33]
#  [14 25 36]]
# [[101 102 103]
#  [204 205 206]]
Related Topics
Common Mistakes
  1. Assuming any two shapes can be combined
  2. Mixing up which axis is stretched
  3. Forgetting a 1-D array aligns with the last axis
Chapter Summary
  • Compare shapes from the right
  • Axes must be equal or 1
  • Size-1 axes stretch
  • Avoids explicit loops and copies
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.