Write Python. Understand every error.

Starting Python in your browser…

NumPy · topic 20 of 25

Arithmetic and broadcasting

Arithmetic between two arrays of the same shape works element by element: the first element with the first, the second with the second, and so on.

price = np.array([40, 25, 60])
qty   = np.array([2, 4, 1])
print(price * qty)    # [80 100 60]

An operation with a single number applies it to every element. NumPy also provides mathematical functions, called ufuncs, that work on whole arrays: np.sqrt, np.exp, np.log, np.abs, np.round(a, 2) and more.

Broadcasting lets NumPy combine arrays of different shapes by stretching the smaller one. Compare the shapes from the right-hand end. Each pair of sizes must be equal, or one of them must be 1.

  • (3, 4) with (4,) works: the row is added to every row
  • (3, 4) with (3, 1) works: the column is added to every column
  • (3, 4) with (3,) fails: 4 and 3 do not match
marks = np.array([[60, 70, 80],
                  [50, 90, 75]])
bonus = np.array([5, 0, 10])      # one bonus per subject
print(marks + bonus)

When a column vector is needed, reshape(-1, 1) turns a 1D array into one column.

In-place operations such as a += 0.5 must keep the array's type. Adding a decimal to an integer array this way is an error; write a = a + 0.5 instead, which creates a new float array.

Key takeaways

  • Arithmetic works element by element: a + 10 adds 10 to every element and a * b multiplies matching elements.
  • Broadcasting stretches a smaller array to match a larger one when the shapes are compatible.
  • A (3, 4) array works with a (4,) row or a (3, 1) column, but not with a (3,) array.
  • Functions such as np.sqrt and np.exp also work on every element.

Common mistakes

  • Combining arrays whose shapes do not match, such as (3, 4) and (3,). Read the ValueError guide.
  • Expecting * to be matrix multiplication. It multiplies matching elements, and @ is the matrix product.

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.