This code picks 3 unique random elements from the array and prints them.
Execution Table
Step
Action
Input Array
Parameters
Random Indices Chosen
Output
1
Start with array
[10, 20, 30, 40, 50]
size=3, replace=False
-
-
2
Check if size > 1
-
size=3
Yes
-
3
Pick 3 unique random indices
-
size=3, replace=False
[1, 4, 0]
-
4
Select elements at indices
-
-
-
[20, 50, 10]
5
Return chosen elements
-
-
-
[20, 50, 10]
💡 3 elements chosen without replacement, execution ends.
Variable Tracker
Variable
Start
After Step 3
After Step 4
Final
arr
[10, 20, 30, 40, 50]
[10, 20, 30, 40, 50]
[10, 20, 30, 40, 50]
[10, 20, 30, 40, 50]
size
3
3
3
3
replace
False
False
False
False
random_indices
None
[1, 4, 0]
[1, 4, 0]
[1, 4, 0]
choice
None
None
[20, 50, 10]
[20, 50, 10]
Key Moments - 3 Insights
Why does numpy.random.choice sometimes return repeated elements?
If replace=True (default), elements can repeat because sampling is with replacement. In the execution_table, replace=False ensures unique picks.
What happens if size is larger than the array length with replace=False?
It causes an error because you cannot pick more unique elements than exist. The execution_table assumes size=3 with array length 5, so no error.
How does numpy.random.choice pick the random indices?
It randomly selects indices from the array range. In the execution_table, indices [1,4,0] were chosen randomly to pick elements [20,50,10].
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'choice' after Step 4?
A[10, 20, 30]
B[20, 50, 10]
C[40, 50, 10]
D[30, 40, 50]
💡 Hint
Check the Output column at Step 4 in the execution_table.
At which step does the function decide to pick multiple elements?
AStep 1
BStep 3
CStep 2
DStep 5
💡 Hint
Look at the 'Check if size > 1' action in the execution_table.
If replace=True, how would the 'random_indices' row change in the execution_table?
AIndices could repeat, e.g., [1, 1, 4]
BIndices would be sorted ascending
CIndices would be reversed
DIndices would be empty
💡 Hint
Recall that replace=True allows repeated picks, so indices can repeat.
Concept Snapshot
numpy.random.choice(array, size=1, replace=True)
- Picks random element(s) from array
- size: number of elements to pick
- replace: if False, picks unique elements
- Returns single element or array
- Useful for random sampling
Full Transcript
This visual trace shows how numpy.random.choice picks random elements from an array. Starting with the array, it checks if multiple elements are requested. If yes, it picks unique random indices (if replace=False) and returns the elements at those indices. Variables like 'choice' update after selection. Key points include understanding replacement behavior and size limits.