random.sample
No position is picked twice, so k can be at most len(population). It works on any sequence including huge ranges (sample(range(10**12), 3) is instant), but sets and dicts must be converted first since Python 3.11.
Demo
import random random.seed(42) random.sample(['a', 'b', 'c', 'd', 'e'], 3)
For a small population sample() copies it into a pool and swaps each pick out; for a large one (here range(1000000)) it keeps a set of chosen indexes and redraws on a collision, so memory stays proportional to k. counts=[4, 2] behaves like the list red, red, red, red, blue, blue: k=7 is too large for those six, and the counts must add up to an int.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| population | Sequence | yes | list, tuple, str or range (a range is never expanded). Not a set or dict. |
| k | int | yes | Sample size, 0 <= k <= len(population); otherwise ValueError. |
| counts | Sequence[int] | no (None) | Keyword-only (3.9+). Repeat counts per element: sample(["red", "blue"], counts=[4, 2], k=5) samples from four reds and two blues. |
Return value
list — A new list of k elements; the population is left unchanged.
Common patterns
import random ticket = sorted(random.sample(range(1, 50), 6))
import random test_idx = set(random.sample(range(len(rows)), k=len(rows) // 5)) test = [r for i, r in enumerate(rows) if i in test_idx] train = [r for i, r in enumerate(rows) if i not in test_idx]
import random scrambled = ''.join(random.sample(word, k=len(word)))
import random winners = random.sample(sorted(entrants), 3)
Examples
Pitfalls
import random random.seed(42) random.sample({'a', 'b', 'c'}, 2)
import random random.seed(42) random.sample(sorted({'a', 'b', 'c'}), 2)
import random random.seed(42) random.sample(['a', 'b', 'c', 'd'])
import random random.seed(42) random.sample(['a', 'b', 'c', 'd'], k=2)
When to use
- Picks without repeats: lottery, raffle, random subset, test split
- Sampling from a huge range without building it
- A shuffled copy of an immutable sequence: sample(seq, k=len(seq))
- Picks with repeats or weights → choices()
- Shuffling a list in place → shuffle()
- Security-relevant selection → secrets.SystemRandom().sample()
Notes
FAQ
random.sample(range(start, stop), k) returns k different integers from start to stop - 1, e.g. random.sample(range(1, 50), 6) for six lottery numbers.