Skip to main content
Albero Academy

Vectorization & Broadcasting

Do maths on whole arrays at once, apply universal functions, and let broadcasting combine different shapes elegantly.

Chapter 3NumPy15 min readBeginner friendly
  • #NumPy
  • #Vectorization
  • #Broadcasting

Vectorization — operating on entire arrays at once instead of element-by-element in a Python loop — is the reason NumPy is fast and expressive. Paired with broadcasting, which lets arrays of different shapes combine, it's how you write real numerical code.

Vectorization

Arithmetic operators work element-wise across a whole array — no loop needed:

element-wise maths
prices = np.array([100, 250, 90, 400])
prices * 1.18 # add 18% GST to every price
prices - prices.mean() # centre each value
prices > 150 # element-wise comparison
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
a + b # [11 22 33] element-wise
a * b # [10 40 90]

Universal functions (ufuncs)

NumPy ships fast, element-wise versions of the maths functions, applied to the whole array at once:

ufuncs
np.sqrt(prices)
np.log(prices)
np.round(prices * 1.18, 2)
np.abs(a - b)
np.exp(a)
np.maximum(a, b) # element-wise max of two arrays

Broadcasting

Broadcasting is the rule that lets NumPy combine arrays of different shapes by virtually stretching the smaller one. A scalar broadcasts to every element; a row vector broadcasts down every row:

stretching shapes to fit
m = np.array([[1, 2, 3],
[4, 5, 6]]) # shape (2, 3)
m + 10 # scalar → added to every element
col_means = m.mean(axis=0) # shape (3,) → [2.5 3.5 4.5]
m - col_means # subtract each column's mean (broadcast down)

np.where — vectorised if/else

np.where(condition, a, b) picks from a where the condition is true and b where it's false — element-wise, no loop:

conditional assignment
scores = np.array([55, 82, 47, 91])
labels = np.where(scores >= 60, "pass", "fail")
# array(['fail', 'pass', 'fail', 'pass'])
# Cap values at 100
capped = np.where(scores > 100, 100, scores)

Practice

Given an array of raw exam scores, write one line to standardise them (subtract the mean, divide by the standard deviation) using broadcasting. Then use np.where to label each as "distinction" (≥75), "pass" (≥40) or "fail".

Key takeaways

  1. 01Vectorization applies operators across whole arrays at once — faster and cleaner than loops.
  2. 02ufuncs (np.sqrt, np.log, np.round…) are fast element-wise maths functions.
  3. 03Broadcasting stretches smaller shapes to fit larger ones — the basis of normalising data.
  4. 04Broadcasting rule: shapes are compatible from the right when equal or one is 1.
  5. 05np.where(cond, a, b) is a vectorised if/else for element-wise selection.