random.sample

Full name
random.sample
Library
random
Syntax

random.sample(population, k, *, counts = None)

Description

The random.sample function returns a list of k elements extracted without repetition of the sequence population. That is, it returns a sample of that sequence. If population contains repeated elements, each of them can be chosen separately as part of the sample.

Repeating elements can be specified one by one, or by the counts parameter. If this exists, it must contain the absolute frequency of each of the population elements, which means that the number of population elements and counts must coincide. So, for example, the following code:

random.sample(["A", "B", "C"], k = 2, counts = [3, 2, 1])

...is equivalent to:

random.sample(["A", "A", "A", "B", "B", "C"], k = 2)

To get a sample of a range of numbers it is recommended to use the range function as an argument (see example below).

Parameters
  • population: Sequence from which to extract the sample without repetition.
  • k: Number of elements to extract.
  • counts: (Optional) Absolute frequencies of the elements of population.
Result

The random.sample function returns a list.

Examples

We can extract a sample made up of two different days of the week with the following code:

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
random.sample(days, 2)
['Friday', 'Saturday']

If our population is the following:

population = ["A", "A", "A", "B", "B", "C"]

...we could extract a sample of two elements without repetition with the following code:

random.sample(population, 2)
['C', 'B']

...or indicating as population the unique values and their absolute frequency:

random.sample(["A", "B", "C"], 2, counts = [3, 2, 1])
['A', 'B']

If we want to extract a sample of, for example, three numbers between 1 and 20, both included, we could obtain it by passing the range function as an argument:

random.sample(range(1, 21), 3)
[10, 3, 8]

Since version 3.9, sets must be converted to lists if we want to extract a sample from them:

s = set([1, 2, 3, 4, 5])
random.sample(list(s), 2)
[3, 5]
Submitted by admin on Thu, 03/11/2021 - 21:24