Bird
0
0

The following code is intended to add two numpy arrays element-wise. What is the error?

medium📝 Debug Q14 of 15
NumPy - Array Operations
The following code is intended to add two numpy arrays element-wise. What is the error?
import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5])
z = x + y
print(z)
AYou cannot add numpy arrays with + operator.
BArrays have different shapes causing a broadcasting error.
CThe arrays must be converted to lists first.
DThe print statement is missing parentheses.
Step-by-Step Solution
Solution:
  1. Step 1: Check array shapes

    Array x has shape (3,), y has shape (2,), so shapes differ.
  2. Step 2: Understand broadcasting rules

    Arrays must be compatible in shape to add; here they are not, causing an error.
  3. Final Answer:

    Arrays have different shapes causing a broadcasting error. -> Option B
  4. Quick Check:

    Shape mismatch = broadcasting error [OK]
Quick Trick: Array shapes must match or broadcast [OK]
Common Mistakes:
  • Thinking + can't add arrays
  • Believing lists are needed
  • Ignoring shape mismatch errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes