Rows 0 and 2 correspond to first and last rows; columns 1 and 3 correspond to second and fourth columns.
Step 2: Extract values from arr at these indices
Row 0: values at cols 1 and 3 are 20 and 40; Row 2: values at cols 1 and 3 are 100 and 120.
Final Answer:
[[ 20 40]
[100 120]] -> Option A
Quick Check:
Selected rows and columns match output [OK]
Hint: Match row and column indices to array positions carefully [OK]
Common Mistakes:
Mixing up row and column indices
Printing wrong slices
Confusing np.ix_() output shape
4. What is wrong with this code snippet?
import numpy as np
arr = np.arange(16).reshape(4,4)
rows = [1, 3]
cols = [0, 2]
result = arr[np.ix_(cols, rows)]
print(result)
medium
A. np.ix_() cannot be used with lists
B. The reshape size is incorrect for np.arange(16)
C. The lists rows and cols contain invalid indices
D. The order of indices in np.ix_() is swapped; rows should come first
Solution
Step 1: Check the order of indices in np.ix_()
np.ix_() expects row indices first, then column indices.
Step 2: Identify the mistake in the code
Here, cols are passed first and rows second, which swaps the intended selection.
Final Answer:
The order of indices in np.ix_() is swapped; rows should come first -> Option D
Quick Check:
Rows first, columns second in np.ix_() [OK]
Hint: Always pass rows first, then columns to np.ix_() [OK]
Common Mistakes:
Passing columns before rows
Misunderstanding reshape dimensions
Thinking np.ix_() only accepts arrays, not lists
5. You have a 3D NumPy array data with shape (4, 5, 6). You want to select slices at indices [1, 3] for the first dimension, [0, 2, 4] for the second, and [2, 5] for the third dimension. Which code correctly uses np.ix_() to get this selection?
hard
A. data[np.ix_([1, 3], [0, 2, 4], [2, 5])]
B. data[np.ix_([0, 2, 4], [1, 3], [2, 5])]
C. data[np.ix_([1, 3], [2, 5], [0, 2, 4])]
D. data[np.ix_([2, 5], [1, 3], [0, 2, 4])]
Solution
Step 1: Identify the dimension order and indices
First dimension indices: [1, 3]; second dimension: [0, 2, 4]; third dimension: [2, 5].
Step 2: Use np.ix_() with indices in correct dimension order
np.ix_() takes indices in order of dimensions: first, second, then third.
Step 3: Confirm the correct option
data[np.ix_([1, 3], [0, 2, 4], [2, 5])] matches the correct order and indices.
Final Answer:
data[np.ix_([1, 3], [0, 2, 4], [2, 5])] -> Option A
Quick Check:
Dimension order matches np.ix_() arguments [OK]
Hint: Pass indices in dimension order to np.ix_() for multi-dim arrays [OK]
Common Mistakes:
Mixing up dimension order in np.ix_()
Using wrong index lists
Assuming np.ix_() works differently for 3D arrays
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.