Challenge - 5 Problems
np.ix_ Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of np.ix_() for 2D mesh indexing
What is the output of the following code snippet using
np.ix_() to create an open mesh grid?NumPy
import numpy as np rows = np.array([1, 3, 5]) cols = np.array([2, 4]) mesh = np.ix_(rows, cols) result = mesh[0] + mesh[1] print(result)
Attempts:
2 left
💡 Hint
Remember that np.ix_ creates open mesh grids that broadcast arrays for indexing.
✗ Incorrect
np.ix_ creates two arrays: one column vector from rows and one row vector from cols. Adding them broadcasts to a 3x2 array where each element is sum of row and column indices.
❓ data_output
intermediate1:30remaining
Shape of arrays from np.ix_()
Given
a = np.array([0, 1, 2]) and b = np.array([10, 20, 30, 40]), what are the shapes of the arrays returned by np.ix_(a, b)?NumPy
import numpy as np a = np.array([0, 1, 2]) b = np.array([10, 20, 30, 40]) mesh = np.ix_(a, b) shapes = (mesh[0].shape, mesh[1].shape) print(shapes)
Attempts:
2 left
💡 Hint
np.ix_ returns arrays shaped to broadcast for indexing: one column vector and one row vector.
✗ Incorrect
np.ix_ returns arrays shaped (len(a),1) and (1,len(b)) to create an open mesh grid for indexing.
🔧 Debug
advanced2:30remaining
Identify the error in using np.ix_() for 3D indexing
What error will the following code raise when using
np.ix_() for 3D indexing?NumPy
import numpy as np x = np.array([0, 1]) y = np.array([2, 3]) z = np.array([4, 5]) mesh = np.ix_(x, y, z) arr = np.arange(60).reshape(3,4,5) result = arr[mesh] print(result.shape)
Attempts:
2 left
💡 Hint
Check how np.ix_ arrays broadcast with the target array shape.
✗ Incorrect
np.ix_ returns arrays shaped (2,1,1), (1,2,1), (1,1,2). Using these to index a (3,4,5) array causes shape mismatch because the indexing arrays cannot broadcast to the same shape.
🚀 Application
advanced1:30remaining
Using np.ix_() to select submatrix
You have a 5x5 matrix
mat. Which option correctly uses np.ix_() to select rows 1, 3 and columns 0, 4 to create a 3x2 submatrix?NumPy
import numpy as np mat = np.arange(25).reshape(5,5)
Attempts:
2 left
💡 Hint
np.ix_ creates open mesh indexing for selecting multiple rows and columns.
✗ Incorrect
Option D uses np.ix_ with correct row and column indices to select a 2x2 submatrix. Option D selects elements at paired indices, not a mesh. Options C and D select wrong rows/columns or slice incorrectly.
🧠 Conceptual
expert2:00remaining
Why use np.ix_() instead of broadcasting arrays directly?
Why is
np.ix_() preferred for open mesh indexing over directly broadcasting arrays for indexing in NumPy?Attempts:
2 left
💡 Hint
Think about how np.ix_ shapes arrays for broadcasting.
✗ Incorrect
np.ix_ reshapes 1D arrays into N-dimensional open mesh grids with singleton dimensions, ensuring they broadcast correctly for indexing without shape conflicts.