Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 14

Arithmetic and Broadcasting

Add, subtract, multiply, divide, and raise arrays element by element, mix in single values with broadcasting, and multiply matrices with @.

Intermediate25 min
Arithmetic and Broadcasting hero Module 23 Lesson 14

Every arithmetic operator works on arrays element by element, and each has a function form such as np.add. When the shapes differ, NumPy stretches the smaller one to fit if it can. That is called broadcasting. Matrix multiplication is a separate operator, @.

Matrix product where row 0 of a and column 0 of b give 13

Operators and functions

+ - * / // % ** each match a function: add, subtract, multiply, divide, floor_divide, mod, and power. Both arrays need the same shape, and / always gives floats.

python
import numpy as np

a = np.array([[10, 20], [30, 40]])
b = np.array([[1, 2], [3, 4]])
print(a + b)
print(np.subtract(a, b))
print(a * b)
print(a / b)
print(a // b, a % b, sep="\n")
print(np.power(b, 2))

Output:

text
[[11 22]
 [33 44]]
[[ 9 18]
 [27 36]]
[[ 10  40]
 [ 90 160]]
[[10. 10.]
 [10. 10.]]
[[10 10]
 [10 10]]
[[0 0]
 [0 0]]
[[ 1  4]
 [ 9 16]]

Broadcasting

A single value is applied to every element. A 1-D array with one value per column is added to every row. A column shaped (rows, 1) is added across every column. If the shapes cannot line up, NumPy raises ValueError.

python
import numpy as np

prices = np.array([120.0, 80.0, 45.0])
print(prices * 1.1)

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

try:
    m + np.array([1, 2])
except ValueError as error:
    print("ValueError:", error)

Output:

text
[132.   88.   49.5]
[[101 202 303]
 [104 205 306]]
[[11 12 13]
 [24 25 26]]
ValueError: operands could not be broadcast together with shapes (2,3) (2,)

Element-wise versus matrix product

* multiplies matching positions. @, np.matmul, and np.dot do matrix multiplication: each result value is a row of the left matrix times a column of the right one, added up. The left matrix needs as many columns as the right one has rows.

python
import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [4, 3]])
print(a * b)
print(a @ b)
print(np.matmul(a, b))
print(np.dot(a, b))

Output:

text
[[ 5 12]
 [12 12]]
[[13 12]
 [31 30]]
[[13 12]
 [31 30]]
[[13 12]
 [31 30]]

Key takeaways

  • Operators run element by element and match functions such as np.add

  • Broadcasting stretches single values, rows, and columns to fit

  • * is element-wise. @ is the matrix product

  • Shapes that cannot line up raise ValueError

  • Next: Statistics

  • Previous: Iterating Arrays

Loading playground…

Check your understanding

Arithmetic and Broadcasting Quiz

What does a * b do for two arrays of the same shape?

1 / 10