Sep-16-2022, 05:50 PM
Sep-16-2022, 06:05 PM
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
From here
Sep-16-2022, 06:11 PM
Read the documentation. I think the docs.python.org documentation is very good.
https://docs.python.org/3/library/random.html
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.
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.
Sep-16-2022, 06:12 PM
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
Sep-16-2022, 08:06 PM
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?Sep-16-2022, 08:10 PM
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()
If you want to eliminate duplicates in the population you can use set()