random.choices(population, weights = None, *, cum_weights = None, k = 1)
The random.choices function returns a list of k randomly drawn elements with replacement of the sequence population.
By default, the probability of each element in population of being extracted is the same, but it can be modified in two ways:
- Specifying the relative weights of each element with the weights parameter. For example, if the sequence population has five elements, passing the list [1, 1, 2, 2, 1] as relative weights would mean that the elements whose indices are 2 and 3 would be twice as likely to be extracted as the other three elements.
- Specifying the accumulated weights with the cum_weights parameter. For example, the list of accumulated weights [1, 2, 4, 6, 7] would be equivalent to the list of relative weights [1, 1, 2, 2, 1].
In both cases, the list of weights must be the same length as population. Relative weights can take the value zero for some elements of population, but if all relative weights are zero, the function returns an error.
As it is an extraction with repetition, the k value can be greater than the number of elements in population.
- population: Sequence from which to extract the elements.
- weights: Relative weights of the elements of population.
- cum_weights: Cumulative weights of the population elements.
- k: Number of elements to extract.
The random.choices function returns a list.
If we start from the following list containing the days of the week:
...we can extract three random days with repetition with the following code:
day
We can specify the weights -relative, in this example- of each element of the sequence from which to extract:
These weights assume that the probability of selecting the value "Saturday" or the value "Sunday" is five times higher than the probability of selecting any other. If we extract, for example, five elements, we can obtain the following result:
n
Some of the weights can take the value zero -but not all-. For example:
n