random.sample(population, k, *, counts = None)
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:
...is equivalent to:
To get a sample of a range of numbers it is recommended to use the range function as an argument (see example below).
- 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.
The random.sample function returns a list.
We can extract a sample made up of two different days of the week with the following code:
If our population is the following:
...we could extract a sample of two elements without repetition with the following code:
...or indicating as population the unique values and their absolute frequency:
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:
Since version 3.9, sets must be converted to lists if we want to extract a sample from them: