Python Forum

Full Version: random.choices and random.sample
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
What is the difference between random.choices and random.sample?
sample() function gives us a specified number of distinct results whereas the choice() function gives us a single value out of the given sequence.

From here
Read the documentation. I think the docs.python.org documentation is very good.

https://docs.python.org/3/library/random.html

Quote:random.choices(population, weights=None, *, cum_weights=None, k=1)
Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.

Quote:random.sample(population, k, *, counts=None)
Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.

Once an element is selected by random.sample() it cannot be selected again. random.choices() can select the same element multiple times. A side effect of this is that random.choices() can return a list that is larger than population (k > len(population)), but random.sample() will raise an exception.
random.choices() was added in Python 3.6 because of a request to add a weights parameter in the random.choice() function. Read What's new in Python 3.6. random.sample() does not have a weights parameter.

Read also the discussion in bpo-18844
When I use
import random
numberList = [11, 19, 29, 21, 21]
print(random.sample(numberList, k=3))
I get an ouput of
Output:
[21, 11, 21]
While I was expecting unique values?
21 appears twice in the population. There are two elements in the population that just happen to have the same value. random.choices() does not eliminate duplicates, it prevents selecting the same element more than once.

If you want to eliminate duplicates in the population you can use set()