60 of 151 menu

The sample method of the random module

The sample method of the random module returns a random sample of elements from a sequence. In the first parameter of the method, we specify the sequence, in the second parameter - the number of elements that we want to select randomly.

In the third optional named parameter k we can specify a list of elements to repeat. This allows us to increase the probability of selecting the given elements. Note that the third parameter of the method was added only starting with Python version 3.9.

Syntax

import random random.sample(sequence, number of elements, [k=repeat repetition iteration reiterative])

Example

Let's get three random elements from the list:

lst = [1, 2, 3, 4, 5] print(random.sample(lst, 3))

Result of code execution:

[2, 1, 5]

Example

Let's also try to take a sample of random elements from the tuple:

tpl = (1, 2, 3, 4, 5) print(random.sample(tpl, 2))

Result of code execution:

[3, 2]

Example

You can also select elements from the sequence generated by the range function:

print(random.sample(range(0, 10), 3))

Result of code execution:

[0, 8, 9]

Example

Now let's take a list and use the counts parameter to assign repetitions to each element in the list. In our case, let the first element be repeated two times, the second three times, and the third four times. We also need to specify the parameter name k to output the number of elements:

lst = [1, 2, 3] print(random.sample(lst, counts=[2, 3, 4], k=3))

This code is equivalent to the following:

lst = [1, 1, 2, 2, 2, 3, 3, 3, 3] # in fact such a list print(random.sample(lst, 3))

Example

Now let's try to take elements from the set:

st = {1, 2, 3, 4, 5} print(random.sample(st, 2))

We will get the following error back:

[5, 2] DeprecationWarning: Sampling from a set deprecated since Python 3.9 and will be removed in a subsequent version. print(random.sample(st, 2))

This is because since Python version 3.9 there is no way to take a sample from a set.

See also

  • method choice of module random,
    which returns a random element from a sequence
  • method random of module random,
    which returns a pseudo-random number
byenru