random.choices

Full name
random.choices
Library
random
Syntax

random.choices(population, weights = None, *, cum_weights = None, k = 1)

Description

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:

  1. 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.
  2. 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.

Parameters
  • 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.
Result

The random.choices function returns a list.

Examples

If we start from the following list containing the days of the week:

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

...we can extract three random days with repetition with the following code:

day = random.choices(population = days, k = 3)
day
['Monday', 'Friday', 'Friday']

We can specify the weights -relative, in this example- of each element of the sequence from which to extract:

weights = [1, 1, 1, 1, 1, 5, 5]

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 = random.choices(days, weights, k = 5)
n
['Tuesday', 'Saturday', 'Friday', 'Sunday', 'Saturday']

Some of the weights can take the value zero -but not all-. For example:

weights = [0, 0, 0, 0, 0, 0, 1]
n = random.choices(days, weights, k = 3)
n
['Sunday', 'Sunday', 'Sunday']
Submitted by admin on Thu, 03/11/2021 - 17:26