0
0
NumPydata~20 mins

1D and 2D broadcasting in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Broadcasting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of 1D and 2D broadcasting addition
What is the output of this code snippet using NumPy broadcasting?
NumPy
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([[10], [20], [30]])
result = arr1 + arr2
print(result)
A
[[11 12 13]
 [21 22 23]
 [31 32 33]]
B
[[11 22 33]
 [21 32 43]
 [31 42 53]]
C
[[10 20 30]
 [11 21 31]
 [12 22 32]]
D
[[1 2 3]
 [10 20 30]
 [11 22 33]]
Attempts:
2 left
💡 Hint
Remember how NumPy aligns shapes for broadcasting: the smaller array is stretched along missing dimensions.
data_output
intermediate
1:30remaining
Shape of result after broadcasting multiplication
Given these arrays, what is the shape of the result after multiplication?
NumPy
import numpy as np

arr1 = np.ones((4,1))
arr2 = np.array([1,2,3])
result = arr1 * arr2
print(result.shape)
A(4, 1)
B(3, 4)
C(4, 3)
D(1, 3)
Attempts:
2 left
💡 Hint
Broadcasting stretches arrays to match each other's shape along missing dimensions.
🔧 Debug
advanced
1:30remaining
Identify the error in broadcasting shapes
What error will this code raise when trying to add these arrays?
NumPy
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([[1, 2], [3, 4]])
result = arr1 + arr2
ANo error, outputs a (2,3) array
BTypeError: unsupported operand type(s) for +: 'list' and 'ndarray'
CIndexError: index out of bounds
DValueError: operands could not be broadcast together with shapes (3,) (2,2)
Attempts:
2 left
💡 Hint
Check if the shapes can be aligned for broadcasting.
visualization
advanced
2:00remaining
Visualize broadcasting result of subtraction
What does the printed array look like after this subtraction with broadcasting?
NumPy
import numpy as np

arr1 = np.array([[5, 10, 15], [20, 25, 30]])
arr2 = np.array([1, 2, 3])
result = arr1 - arr2
print(result)
A
[[ 6 12 18]
 [21 27 33]]
B
[[ 4  8 12]
 [19 23 27]]
C
[[ 4  8 12]
 [ 1  2  3]]
D
[[ 4  8 12]
 [19 23 27]
 [ 4  8 12]]
Attempts:
2 left
💡 Hint
Broadcast arr2 across rows of arr1 and subtract element-wise.
🧠 Conceptual
expert
2:30remaining
Why does broadcasting fail for these shapes?
Given arrays with shapes (3,1) and (2,3), why does broadcasting fail when trying to add them?
ABecause the dimensions are not compatible: 1 and 3 can broadcast, but 3 and 2 cannot.
BBecause both arrays have different numbers of dimensions, broadcasting is not allowed.
CBecause the arrays have the same total number of elements but different shapes.
DBecause broadcasting requires both arrays to have the same shape exactly.
Attempts:
2 left
💡 Hint
Broadcasting compares shapes from the right side dimension-wise.