Lesson 2 · Unit 01
Broadcasting
How arrays of different shapes combine, and the bug that hides there
What you practise
- The alignment rule read right to left, stretching a size-1 axis, adding a row to every row, the shape errors it causes and the silent bugs it hides
Try a question from this lesson
Pick one
a has 3 rows of 2 numbers and b has just 2 numbers. NumPy adds them without complaint. What is the last row of the result?
import numpy as np
a = np.array([[1, 2],
[3, 4],
[5, 6]])
b = np.array([10, 20])
print((a + b)[2])Correct answer
[15 26]
Why
b is added to every row: 5 + 10 and 6 + 20. NumPy behaves as if b were stacked three times to match a. This stretching of the smaller array is called broadcasting.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Line the shapes up from the right
To combine two arrays, NumPy compares their shapes from the last axis backwards.
Two sizes fit if they are equal or one of them is 1. A missing axis counts as 1. Every size-1 axis is stretched to match the other array. Anything else is an error.
a (3, 2)
b (2,) read as (1, 2)
a + b (3, 2) b meets every row
c (3, 1)
d (1, 4)
c + d (3, 4) both stretch10 more exercises in the app
- 3× multiple choice
- 4× type the answer
- 1× order the lines
- 1× true or false
- 1× fill the blanks
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.