Bird
Raised Fist0
NumPydata~10 mins

Random choice from array in NumPy - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Random choice from array
Start with array
↓
Call numpy.random.choice
↓
Check if size > 1?
No→Pick single random element
Yes↓
Pick multiple random elements
↓
Return chosen element(s)
The function takes an array and picks one or more random elements from it, returning the result.
Execution Sample
NumPy
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
choice = np.random.choice(arr, size=3, replace=False)
print(choice)
This code picks 3 unique random elements from the array and prints them.
Execution Table
StepActionInput ArrayParametersRandom Indices ChosenOutput
1Start with array[10, 20, 30, 40, 50]size=3, replace=False--
2Check if size > 1-size=3Yes-
3Pick 3 unique random indices-size=3, replace=False[1, 4, 0]-
4Select elements at indices---[20, 50, 10]
5Return chosen elements---[20, 50, 10]
💡 3 elements chosen without replacement, execution ends.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
arr[10, 20, 30, 40, 50][10, 20, 30, 40, 50][10, 20, 30, 40, 50][10, 20, 30, 40, 50]
size3333
replaceFalseFalseFalseFalse
random_indicesNone[1, 4, 0][1, 4, 0][1, 4, 0]
choiceNoneNone[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.

Practice

(1/5)
1.

What does the numpy.random.choice function do?

easy
A. It picks one or more random elements from an array.
B. It sorts the array in ascending order.
C. It calculates the mean of the array elements.
D. It removes duplicate elements from the array.

Solution

  1. Step 1: Understand the function purpose

    numpy.random.choice is used to select random elements from an array.
  2. Step 2: Compare with other options

    Sorting, calculating mean, or removing duplicates are different functions and unrelated to random choice.
  3. Final Answer:

    It picks one or more random elements from an array. -> Option A
  4. Quick Check:

    Random choice = pick random elements [OK]
Hint: Random choice picks elements randomly from an array [OK]
Common Mistakes:
  • Confusing random choice with sorting
  • Thinking it calculates statistics like mean
  • Assuming it removes duplicates
2.

Which of the following is the correct syntax to pick 3 random elements from a numpy array arr with replacement?

import numpy as np
arr = np.array([10, 20, 30, 40, 50])
easy
A. np.random.choice(arr, size=3, replace=False)
B. np.random.choice(arr, 3, replace=False)
C. np.random.choice(arr, size=3, replace=True)
D. np.random.choice(arr, 3, replace=True, axis=1)

Solution

  1. Step 1: Check correct parameter names

    The function uses size to specify number of elements and replace to allow repeats.
  2. Step 2: Validate each option

    np.random.choice(arr, size=3, replace=True) uses correct parameters: size=3 and replace=True. Others have wrong parameter names or extra invalid ones.
  3. Final Answer:

    np.random.choice(arr, size=3, replace=True) -> Option C
  4. Quick Check:

    Correct syntax = size=3, replace=True [OK]
Hint: Use size= and replace= parameters correctly [OK]
Common Mistakes:
  • Using positional argument without size=
  • Setting replace=False when repeats are needed
  • Adding invalid parameters like axis
3.

What is the output of this code?

import numpy as np
np.random.seed(0)
arr = np.array([1, 2, 3, 4, 5])
result = np.random.choice(arr, size=4, replace=False)
print(result)
medium
A. [5 1 4 3]
B. [4 5 1 3]
C. [1 2 3 4]
D. [2 5 1 4]

Solution

  1. Step 1: Understand seed and choice without replacement

    Setting seed ensures reproducible random results. Choosing 4 unique elements without replacement picks 4 different values from arr.
  2. Step 2: Run code or recall output

    With seed 0, the output is [2 5 1 4].
  3. Final Answer:

    [2 5 1 4] -> Option D
  4. Quick Check:

    Seed 0 + replace=False = [2 5 1 4] [OK]
Hint: Use np.random.seed for consistent random output [OK]
Common Mistakes:
  • Ignoring seed and expecting different output
  • Confusing replace=True and replace=False results
  • Assuming output is sorted
4.

Identify the error in this code snippet:

import numpy as np
arr = np.array([1, 2, 3])
result = np.random.choice(arr, size=5, replace=False)
print(result)
medium
A. Size is larger than array length without replacement, causing an error.
B. Array is not defined properly.
C. Missing import statement for numpy.
D. replace parameter should be True to avoid error.

Solution

  1. Step 1: Check size vs array length with replace=False

    Choosing 5 elements without replacement from an array of length 3 is invalid and raises an error.
  2. Step 2: Confirm other parts are correct

    Array is defined, numpy is imported, and replace parameter is valid. The main issue is size too large without replacement.
  3. Final Answer:

    Size is larger than array length without replacement, causing an error. -> Option A
  4. Quick Check:

    Size > array length + replace=False = error [OK]
Hint: Size must not exceed array length if replace=False [OK]
Common Mistakes:
  • Ignoring size vs array length mismatch
  • Assuming replace=True by default
  • Not importing numpy before use
5.

You have a numpy array data = np.array([10, 20, 30, 40, 50]). You want to randomly select 3 unique elements but ensure the number 20 is always included in the result. Which approach is correct?

hard
A. Pick 3 elements with replacement and filter for 20 after.
B. Remove 20 from array, pick 2 without replacement, then add 20 back.
C. Use np.random.choice(data, size=3, replace=False) directly.
D. Pick 3 elements with replacement and add 20 manually.

Solution

  1. Step 1: Understand the requirement

    We want 3 unique elements including 20 always.
  2. Step 2: Choose method to guarantee 20

    Remove 20, pick 2 unique elements from remaining, then add 20 to result ensures 20 is included and no duplicates.
  3. Step 3: Evaluate other options

    Direct random choice may exclude 20. Picking with replacement can cause duplicates or exclude 20. Adding 20 manually after picking with replacement may cause duplicates.
  4. Final Answer:

    Remove 20 from array, pick 2 without replacement, then add 20 back. -> Option B
  5. Quick Check:

    Guarantee element by picking rest then adding it [OK]
Hint: Pick others without 20, then add 20 to ensure inclusion [OK]
Common Mistakes:
  • Assuming random choice always includes 20
  • Using replacement causing duplicates
  • Adding 20 after picking with replacement causing repeats