Bird
Raised Fist0
NumPydata~10 mins

1D and 2D broadcasting in NumPy - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - 1D and 2D broadcasting
Start with arrays
↓
Check shapes
↓
Align dimensions
↓
Broadcast smaller array
↓
Perform element-wise operation
↓
Output result
Broadcasting matches array shapes by expanding smaller arrays to perform element-wise operations.
Execution Sample
NumPy
import numpy as np
A = np.array([[1,2,3],[4,5,6]])
B = np.array([10,20,30])
C = A + B
print(C)
Add a 2D array and a 1D array using broadcasting to get a 2D result.
Execution Table
StepA shapeB shapeBroadcasted B shapeOperationResult element example
1(2,3)(3,)(2,3)Broadcast B to match AB becomes [[10,20,30],[10,20,30]]
2(2,3)(3,)(2,3)Add A and broadcasted B element-wiseC[0,0] = 1 + 10 = 11
3(2,3)(3,)(2,3)Add A and broadcasted B element-wiseC[1,2] = 6 + 30 = 36
4(2,3)(3,)(2,3)Final result C[[11,22,33],[14,25,36]]
💡 Broadcasting completes when shapes align and operation finishes.
Variable Tracker
VariableStartAfter BroadcastFinal
A[[1,2,3],[4,5,6]][[1,2,3],[4,5,6]][[1,2,3],[4,5,6]]
B[10,20,30][[10,20,30],[10,20,30]][[10,20,30],[10,20,30]]
CN/AN/A[[11,22,33],[14,25,36]]
Key Moments - 2 Insights
Why does B get repeated to match A's shape?
Because B has shape (3,) and A has (2,3), numpy repeats B along the missing dimension to (2,3) so element-wise addition works, as shown in execution_table step 1.
Can broadcasting happen if shapes are incompatible?
No, broadcasting requires dimensions to be equal or one of them to be 1. Here, B's shape (3,) is compatible with A's (2,3) because 3 matches and 2 can be broadcasted.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the shape of B after broadcasting at step 1?
A(2,3)
B(3,)
C(1,3)
D(3,2)
💡 Hint
Check the 'Broadcasted B shape' column at step 1 in execution_table.
At which step does the element-wise addition start in the execution_table?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for the first step mentioning 'Add A and broadcasted B element-wise'.
If B was shape (2,1) instead of (3,), what would happen to broadcasting?
AB would broadcast to (3,2)
BBroadcasting would fail due to incompatible shapes
CB would broadcast to (2,3) by repeating the second dimension
DB would remain (2,1) and no operation possible
💡 Hint
Recall broadcasting rules: dimension 1 can be stretched to match 3.
Concept Snapshot
1D and 2D broadcasting in numpy:
- Smaller array expands to match larger array shape
- Dimensions must be equal or 1
- Enables element-wise operations without explicit loops
- Example: (2,3) + (3,) broadcasts (3,) to (2,3)
- Result shape matches the larger array
Full Transcript
This lesson shows how numpy broadcasting works between 1D and 2D arrays. We start with two arrays: A with shape (2,3) and B with shape (3,). Because B has fewer dimensions, numpy repeats it along the missing dimension to shape (2,3). Then element-wise addition happens between A and broadcasted B. The final result is a (2,3) array where each element is the sum of corresponding elements from A and B. Broadcasting requires dimensions to be equal or one of them to be 1. This allows simple, efficient operations without manual loops.

Practice

(1/5)
1. What does broadcasting in NumPy allow you to do with arrays of different shapes?
easy
A. Only add arrays if they have the exact same shape
B. Sort arrays in ascending order
C. Convert arrays into lists automatically
D. Perform element-wise operations without manually reshaping arrays

Solution

  1. Step 1: Understand broadcasting concept

    Broadcasting lets NumPy perform math on arrays with different shapes by stretching smaller arrays.
  2. Step 2: Identify what broadcasting enables

    This means you can do element-wise operations without manually reshaping arrays to the same shape.
  3. Final Answer:

    Perform element-wise operations without manually reshaping arrays -> Option D
  4. Quick Check:

    Broadcasting = element-wise operations on different shapes [OK]
Hint: Broadcasting stretches smaller arrays to match bigger ones [OK]
Common Mistakes:
  • Thinking arrays must have the same shape to operate
  • Confusing broadcasting with sorting or reshaping
  • Assuming broadcasting copies data
2. Which of the following is the correct way to add a 1D array b = np.array([1, 2, 3]) to each row of a 2D array a with shape (4, 3)?
easy
A. a + b
B. a + b.T
C. a + b.reshape(3, 1)
D. a + b.reshape(1, 4)

Solution

  1. Step 1: Check shapes of arrays

    Array a has shape (4, 3), and b has shape (3,). Adding a + b broadcasts b across rows.
  2. Step 2: Understand broadcasting rules

    Since b matches the number of columns, it adds to each row correctly without reshaping.
  3. Final Answer:

    a + b -> Option A
  4. Quick Check:

    1D array added across rows = a + b [OK]
Hint: Add 1D array directly if its length matches columns [OK]
Common Mistakes:
  • Trying to transpose 1D array which has no effect
  • Reshaping to wrong dimensions causing errors
  • Confusing rows and columns in shapes
3. What is the output of the following code?
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([10, 20, 30])
result = a + b
print(result)
medium
A. [[11 22 33] [14 25 36]]
B. [[11 12 13] [14 15 16]]
C. [[10 20 30] [10 20 30]]
D. Error due to shape mismatch

Solution

  1. Step 1: Analyze shapes and operation

    a shape is (2,3), b shape is (3,). Adding broadcasts b across rows.
  2. Step 2: Calculate element-wise addition

    Row 1: [1+10, 2+20, 3+30] = [11, 22, 33]
    Row 2: [4+10, 5+20, 6+30] = [14, 25, 36]
  3. Final Answer:

    [[11 22 33] [14 25 36]] -> Option A
  4. Quick Check:

    Broadcast add across rows = [[11 22 33], [14 25 36]] [OK]
Hint: Add 1D array to 2D rows matches columns [OK]
Common Mistakes:
  • Expecting error due to different shapes
  • Adding element-wise without broadcasting
  • Confusing rows and columns in addition
4. Identify the error in this code snippet:
import numpy as np
a = np.array([[1, 2], [3, 4], [5, 6]])
b = np.array([10, 20, 30])
result = a + b
print(result)
medium
A. Using wrong operator for addition
B. Syntax error in array creation
C. Shapes of a and b are incompatible for broadcasting
D. No error, code runs fine

Solution

  1. Step 1: Check shapes of arrays

    a shape is (3, 2), b shape is (3,). They differ in second dimension.
  2. Step 2: Understand broadcasting rules

    Broadcasting requires trailing dimensions to match or be 1. Here, 2 != 3, so addition fails.
  3. Final Answer:

    Shapes of a and b are incompatible for broadcasting -> Option C
  4. Quick Check:

    Shape mismatch causes broadcasting error [OK]
Hint: Check trailing dimensions match or are 1 for broadcasting [OK]
Common Mistakes:
  • Assuming any shapes can broadcast
  • Ignoring dimension order in arrays
  • Thinking 1D arrays always broadcast to 2D
5. You have a 2D array data of shape (5, 4) representing 5 samples with 4 features each. You want to subtract the mean of each feature (given as a 1D array mean_vals of length 4) from the corresponding feature column in data. Which code correctly applies broadcasting to do this?
hard
A. data - mean_vals.reshape(4, 1)
B. data - mean_vals
C. data - mean_vals.reshape(1, 5)
D. data - mean_vals.T

Solution

  1. Step 1: Understand shapes and operation

    data shape is (5, 4), mean_vals shape is (4,). Subtracting mean_vals from data broadcasts mean_vals across rows.
  2. Step 2: Confirm correct broadcasting

    Since mean_vals length matches columns, data - mean_vals subtracts feature-wise means correctly.
  3. Final Answer:

    data - mean_vals -> Option B
  4. Quick Check:

    Subtract 1D array from 2D rows = data - mean_vals [OK]
Hint: Subtract 1D array matching columns directly [OK]
Common Mistakes:
  • Reshaping mean_vals incorrectly causing errors
  • Transposing 1D array which has no effect
  • Trying to subtract mean_vals across wrong axis
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard