choice, shuffle & permutation
Picking random items from an existing array (with or without replacement, with weights) and randomly reordering arrays in place or as a copy.
Watch the lesson
1 video on CodeWithMunnaX
So far we generated new numbers. Very often you want randomness over things you already have: pick a random team to host the next match, pick 4 players for a dope test, simulate an over ball by ball with realistic probabilities, or shuffle the batting order. That is what choice, shuffle and permutation do.
Definition
np.random.choice(a, size=None, replace=True, p=None)draws a random sample from the elements of a 1D arraya(or fromnp.arange(a)ifais an int).
np.random.shuffle(x)randomly reorders the arrayxin place (it changesxitself and returnsNone).
np.random.permutation(x)returns a new, shuffled copy ofx(leavingxuntouched); ifxis an intn, it returns a shufflednp.arange(n).
- Sample — a subset of items picked from a population (here, the array).
- With replacement (
replace=True) — after an item is picked it is "put back", so it can be picked again. Like rolling a dice repeatedly. - Without replacement (
replace=False) — each item can be picked at most once. Like drawing names out of a hat. - Weights (
p=) — a probability for each element; they must be non-negative and sum to 1. - In place — the original object is modified; nothing new is created.
Syntax
python
np.random.choice(a, size=None, replace=True, p=None)
np.random.shuffle(x) # returns None, modifies x
np.random.permutation(x) # returns a new array| Parameter | Meaning | Default |
|---|---|---|
a | 1D array/list to pick from, or an int n meaning np.arange(n) | — required |
size | How many to pick (int or shape tuple) | None → one item |
replace | True: items can repeat. False: every pick is unique | True |
p | Probabilities for each item, same length as a, sum = 1 | None → all equally likely |
x (shuffle) | Array or list to reorder in place; for 2D only rows move | — required |
x (permutation) | Array to copy-and-shuffle, or int n | — required |
Example — picking teams
python
import numpy as np
np.random.seed(42)
teams = np.array(["CSK", "MI", "RCB", "KKR", "SRH", "RR"])
print(np.random.choice(teams)) # one team
print(np.random.choice(teams, size=4)) # 4 picks, repeats allowed
print(np.random.choice(teams, size=4, replace=False)) # 4 different teamstext
KKR
['SRH' 'RCB' 'SRH' 'SRH']
['RR' 'CSK' 'KKR' 'SRH']How it works: with the default replace=True, SRH came up three times — legal, because every pick is independent. With replace=False the 4 teams are guaranteed to be different (great for "pick 4 teams for the playoffs").
Example — weighted picks with p=: simulate an over
python
np.random.seed(42)
outcomes = ["dot", "1", "2", "4", "6", "W"]
probs = [0.40, 0.30, 0.10, 0.10, 0.05, 0.05] # must add up to 1
over = np.random.choice(outcomes, size=6, p=probs)
print("One over:", over)
balls = np.random.choice(outcomes, size=10_000, p=probs)
values, counts = np.unique(balls, return_counts=True)
for v, c in zip(values, counts):
print(f"{v:>3}: {c / len(balls):.3f}")text
One over: ['dot' 'W' '2' '1' 'dot' 'dot']
1: 0.306
2: 0.092
4: 0.100
6: 0.049
W: 0.047
dot: 0.406How it works: p makes "dot" 8 times more likely than "6". Over 10,000 balls the observed frequencies come very close to the probabilities we set (0.40, 0.30, 0.10 …). This is the heart of Monte Carlo simulation.
Example — choice with an int, and an impossible sample
python
np.random.seed(42)
print(np.random.choice(5, size=3)) # same as choosing from np.arange(5)
try:
np.random.choice(["CSK", "MI"], size=3, replace=False)
except ValueError as e:
print("ValueError:", e)text
[3 4 2]
ValueError: Cannot take a larger sample than population when 'replace=False'You cannot pick 3 different teams from a list of 2.
Example — shuffle (in place) vs permutation (copy)
python
np.random.seed(42)
order = np.array(["Rohit", "Virat", "Shubman", "Shreyas", "Hardik"])
result = np.random.shuffle(order)
print("returned:", result)
print("order is now:", order)text
returned: None
order is now: ['Virat' 'Hardik' 'Shubman' 'Rohit' 'Shreyas']python
np.random.seed(42)
order = np.array(["Rohit", "Virat", "Shubman", "Shreyas", "Hardik"])
new_order = np.random.permutation(order)
print("original :", order)
print("permuted :", new_order)
print(np.random.permutation(5))text
original : ['Rohit' 'Virat' 'Shubman' 'Shreyas' 'Hardik']
permuted : ['Virat' 'Hardik' 'Shubman' 'Rohit' 'Shreyas']
[3 1 2 0 4]How it works: shuffle rearranged order itself and gave back None. permutation produced the same new order (same seed) but kept the original safe. permutation(5) is a shuffled [0 1 2 3 4] — perfect as random indices.
Example — shuffling a 2D array moves whole rows
python
np.random.seed(42)
m = np.arange(12).reshape(4, 3)
np.random.shuffle(m) # rows move, each row stays intact
print(m)text
[[ 3 4 5]
[ 9 10 11]
[ 0 1 2]
[ 6 7 8]]Only axis 0 is shuffled — each player's row of stats stays together, which is exactly what you want when shuffling a dataset of records.
Comparison — shuffle vs permutation
np.random.shuffle(x) | np.random.permutation(x) | |
|---|---|---|
| Changes the original? | Yes (in place) | No (returns a copy) |
| Return value | None | new shuffled array |
| Accepts an int? | No | Yes → shuffled arange(n) |
| Memory | no extra copy | one extra copy |
| Use when | you don't need the old order | you need both orders, or random indices |
Common mistakes
- ❌
order = np.random.shuffle(order)— noworderisNone! ✅ Just callnp.random.shuffle(order), or useorder = np.random.permutation(order). - ❌ Weights that don't sum to 1 (e.g.
p=[0.5, 0.3]) →ValueError: probabilities do not sum to 1. ✅ Normalise:p = w / w.sum(). - ❌ Passing a 2D array to
choice→ValueError: a must be 1-dimensional. ✅ Pick random row indices instead:data[np.random.choice(len(data), 3)]. - ❌ Shuffling features and labels separately (they get out of sync). ✅ Make one
idx = np.random.permutation(n)and useX[idx],y[idx].
Interview tip
Q: How would you shuffle a dataset X and its labels y so they stay matched?
A: Generate one permutation of indices, idx = np.random.permutation(len(X)), and index both arrays with it: X[idx], y[idx].
Key points to remember
- choice(a, size, replace, p) samples elements from an existing 1D array (or from arange(n) if a is an int).
- replace=True lets an item be picked again; replace=False guarantees unique picks.
- p= gives each item a probability; the list must match a's length and sum to 1.
- shuffle(x) reorders x in place and returns None.
- permutation(x) returns a shuffled copy and leaves x unchanged; permutation(n) gives shuffled indices 0..n-1.
- On 2D arrays both shuffle and permutation only reorder rows (axis 0).
- Shuffle X and y together with one shared index array from permutation.
Try it yourself
Weighted ball-by-ball over simulator
shuffle vs permutation
Shuffle features and labels together
Practice: pick your playoff teams
Revision Flashcards
Tap a card to flip it and see the answer.
