Bird
0
0

What is the output of the following code?

medium📝 Predict Output Q13 of 15
NumPy - Broadcasting
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)
A[[11 22 33] [14 25 36]]
B[[11 12 13] [14 15 16]]
C[[10 20 30] [10 20 30]]
DError due to shape mismatch
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes