In this tutorial, you’ll learn how to use random.sample() to pick multiple unique items from a list, string, set or dictionary, and how to take a random sample of rows from a NumPy array.
The sample() function of the random module returns a new list of k items chosen randomly from a population, without replacement: no position is picked twice. For example, if you have a list of 100 names and want 10 different names, use random.sample().
Note: To pick a single item, use random.choice() instead.
| Operation | Description |
|---|---|
random.sample(seq, k) | Return k unique items from a list, tuple, string or range (sampling without replacement) |
random.choices(seq, k=n) | Return n items that may repeat (sampling with replacement) |
random.sample(range(100), 5) | Return 5 unique random integers from 0 to 99 |
random.sample(sorted(a_set), 2) | Return 2 random items from a set |
random.sample(list(d.items()), 2) | Return 2 random key-value pairs from a dictionary |
Table of contents
- How to use random.sample()
- Random sample with replacement (repeats allowed)
- Generate a list of unique random integers
- Random sample from a string
- A random sample from a set
- Random sample from a dictionary
- Repeat elements using the counts parameter
- Get the same sample every time
- Get random rows from a multidimensional array
- Secure random sample
- random.sample() errors
- Summary
How to use random.sample()
Syntax
random.sample(population, k, *, counts=None)Code language: Python (python)
population: a sequence such as a list, tuple, string orrange. Sets and dictionaries must be converted first (see below).k: the number of items to select. It must be between 0 and the population size.counts(optional, Python 3.9+): how many times each element appears in the population.
It returns a new list with k randomly selected items.
Example: select multiple items from a list without repetition
Output (your result may differ):
[120, 80, 100] [20, 40, 80, 100, 120]
Points to remember about random.sample()
- It doesn’t modify the original sequence; it returns a new list.
- The elements don’t need to be hashable or unique.
- Each position is picked at most once. If the population contains duplicate values, the sample can contain them too.
Output:
[20, 60, 40, 20]
Tip: To sample unique values, remove duplicates first: random.sample(sorted(set(example_list)), 3).
Random sample with replacement (repeats allowed)
If the same item may be picked more than once, use random.choices() (Python 3.6+). Unlike sample(), k can be larger than the population.
Output:
['Maria', 'Maria', 'Rafael']
Generate a list of unique random integers
random.randint() can return the same number twice. To get unique random integers, pass a range() to sample(). A range doesn’t store its numbers in memory, so this is fast even for very large ranges.
Output:
[6, 20, 14, 47, 60] [16, 25, 35, 7, 37, 49]
Tip: random.sample(a_list, k=len(a_list)) returns a shuffled copy of a list without changing the original. See how to shuffle a list.
Random sample from a string
A string is a sequence, so sample() returns a list of random characters. Use "".join() to turn it back into a string.
Output:
['e', 'Y', 'v'] eYv
A random sample from a set
Since Python 3.11, sample() no longer accepts a set and raises TypeError: Population must be a sequence. For dicts or sets, use sorted(d). Convert the set to a sorted list first. Sorting also makes the result reproducible when you use a seed.
Output:
['Emma', 'Eric', 'Kelly']
Random sample from a dictionary
A dictionary isn’t a sequence either. Convert its items to a list, then sample key-value pairs.
Output:
[('Donald', 60), ('Kelly', 55)]
Donald 60
Kelly 55
Use dict(sampled_items) if you need the result as a dictionary.
Repeat elements using the counts parameter
The counts argument (Python 3.9+) lets you describe a population with repeated elements without building the full list. For example, a bag with 3 red balls and 2 blue balls:
Output:
['blue', 'red', 'red', 'red']
Get the same sample every time
To reproduce a sample, for example in tests, set the same value with random.seed() before calling sample().
Output:
[40.5, 30.5, 20.5] [40.5, 30.5, 20.5] [40.5, 30.5, 20.5]
Get random rows from a multidimensional array
To pick several random rows from a 2D NumPy array without repeating any row, use the choice() method of a NumPy Generator with replace=False.
Output:
[[ 6 12 18] [ 5 10 15] [ 7 14 21]]
Secure random sample
The random module is predictable and not suitable for security. For security-sensitive samples, use a cryptographically secure random generator: random.SystemRandom().sample(). Read more in the secrets module tutorial.
random.sample() errors
ValueError: Sample larger than population or is negative:kis greater than the population size or negative.TypeError: Random.sample() missing 1 required positional argument: 'k': you didn’t passk.TypeError: Population must be a sequence: you passed a set or dictionary (Python 3.11+).
Practice Problem:
A class has 10 students. Randomly pick 3 different students to present today and print their names.
Show Solution
Summary
random.sample(population, k)returnskitems without picking any position twice.- Use
random.choices()when repeats are allowed. - Convert sets with
sorted()and dictionaries withlist(d.items())before sampling. - Use
random.seed()for reproducible samples andSystemRandomfor secure ones.
Now test what you’ve learned with the Python random data generation exercise and quiz.
