Passing an integer for a is shorthand for sampling from a range up to that integer, a common convenience for picking random indices. By default, replace=True means the same element can be selected more than once, even within a single call requesting multiple samples; setting replace=False instead samples without replacement, guaranteeing every selected element is distinct, similar to drawing cards from a deck without putting them back. The p parameter lets you assign a custom probability to each element instead of assuming a uniform distribution over all of them.
1Understanding np.random.choice()
Passing an integer for a is shorthand for sampling from a range up to that integer, a common convenience for picking random indices. By default, replace=True means the same element can be selected more than once, even within a single call requesting multiple samples; setting replace=False instead samples without replacement, guaranteeing every selected element is distinct, similar to drawing cards from a deck without putting them back. The p parameter lets you assign a custom probability to each element instead of assuming a uniform distribution over all of them.
Set replace=False specifically when you need a random subset with no duplicates, like randomly selecting several distinct items from a list — the default, replace=True, can select the very same element more than once.
import numpy as np
np.random.seed(0)
colors = np.array(["red", "green", "blue", "yellow"])
print(np.random.choice(colors, size=3))2Practical Example
Here is a real-world application of np.random.choice() showing how it is used in production NumPy code.
import numpy as np
np.random.seed(0)
weighted = np.random.choice(["heads", "tails"], size=5, p=[0.9, 0.1])
print(weighted)3Best Practices
Follow these guidelines when working with np.random.choice():
1. Set replace=False when sampling should never select the same element twice, like choosing a subset of distinct items
2. Use the p parameter to draw from a weighted/non-uniform distribution instead of manually implementing weighted sampling
3. Pass an integer for a as a convenient shorthand for sampling random indices from a range, instead of building the range array explicitly
Tip: Set replace=False specifically when you need a random subset with no duplicates, like randomly selecting several distinct items from a list — the default, replace=True, can select the very same element more than once.
import numpy as np
np.random.seed(0)
colors = np.array(["red", "green", "blue", "yellow"])
print(np.random.choice(colors, size=3))