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
intermediate1: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)
Attempts:
2 left
💡 Hint
np.take selects elements from the array at the given indices, including repeats.
✗ Incorrect
np.take(arr, indices) returns elements at positions 1, 3, 1, and 4 from arr, which are 20, 40, 20, and 50 respectively.
❓ data_output
intermediate1: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)
Attempts:
2 left
💡 Hint
np.put replaces elements at specified indices with given values.
✗ Incorrect
np.put replaces arr[0] with 50, arr[2] with 150, and arr[4] with 250, resulting in [50, 10, 150, 20, 250].
🔧 Debug
advanced1: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)
Attempts:
2 left
💡 Hint
Check if the length of values matches the length of indices.
✗ Incorrect
np.put expects the values array to be broadcastable to the shape of indices. Here, values has length 2 but indices length 3, causing a ValueError.
🚀 Application
advanced2: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])
Attempts:
2 left
💡 Hint
Use np.take to get values, then np.put with reversed values to swap.
✗ Incorrect
Option B correctly takes elements at indices 1 and 3, reverses them, and puts them back at the same indices, swapping the values.
🧠 Conceptual
expert2: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)
Attempts:
2 left
💡 Hint
mode='wrap' wraps indices around the array length.
✗ Incorrect
Indices 5 and 7 wrap to 0 and 2 respectively (5 % 5 = 0, 7 % 5 = 2). So values are put at positions 0, 0, and 2 in order, last write wins at position 0.