0
0
NumPydata~20 mins

np.take() and np.put() for advanced selection in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
np.take() and np.put() Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1:30remaining
Output of np.take() with repeated indices
What is the output of the following code snippet?
NumPy
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
indices = [1, 3, 1, 4]
result = np.take(arr, indices)
print(result)
A[20 40 20 50]
B[10 30 10 50]
C[20 40 40 50]
D[10 20 30 40]
Attempts:
2 left
💡 Hint
np.take selects elements from the array at the given indices, including repeats.
data_output
intermediate
1:30remaining
Result of np.put() modifying array elements
Given the code below, what is the final state of the array 'arr' after np.put() is called?
NumPy
import numpy as np
arr = np.array([5, 10, 15, 20, 25])
indices = [0, 2, 4]
values = [50, 150, 250]
np.put(arr, indices, values)
print(arr)
A[50 10 150 20 250]
B[5 10 15 20 25]
C[50 150 250 20 25]
D[250 10 150 20 50]
Attempts:
2 left
💡 Hint
np.put replaces elements at specified indices with given values.
🔧 Debug
advanced
1:30remaining
Identify the error in np.put usage
What error will the following code produce when executed?
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
indices = [0, 1, 2]
values = [10, 20]
np.put(arr, indices, values)
ANo error, array modified successfully
BIndexError: index 3 is out of bounds for axis 0 with size 4
CTypeError: 'list' object is not callable
DValueError: could not broadcast input array from shape (2,) into shape (3,)
Attempts:
2 left
💡 Hint
Check if the length of values matches the length of indices.
🚀 Application
advanced
2:00remaining
Using np.take() and np.put() to swap elements
You want to swap the elements at positions 1 and 3 in the array below using np.take() and np.put(). Which code snippet correctly performs this swap?
NumPy
import numpy as np
arr = np.array([100, 200, 300, 400, 500])
A
temp = np.take(arr, [1, 3])
np.put(arr, [3, 1], temp)
B
temp = np.take(arr, [1, 3])
np.put(arr, [1, 3], temp[::-1])
Cnp.put(arr, [1, 3], [arr[3], arr[1]])
Darr[[1, 3]] = arr[[3, 1]]
Attempts:
2 left
💡 Hint
Use np.take to get values, then np.put with reversed values to swap.
🧠 Conceptual
expert
2:00remaining
Effect of mode parameter in np.put()
Consider the array and code below. What will be the final array after executing np.put() with mode='wrap'?
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
indices = [0, 5, 7]
values = [10, 20, 30]
np.put(arr, indices, values, mode='wrap')
print(arr)
A[10 20 30 4 5]
BIndexError: index 5 is out of bounds for axis 0 with size 5
C[20 2 30 4 5]
D[10 2 3 4 5]
Attempts:
2 left
💡 Hint
mode='wrap' wraps indices around the array length.