Thursday 23 September 2021

Python: Select random elements from a list, sequence

'random.sample' method is used to select k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.

 

Signature

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

 

population – actual list or sequence

k – Number of elements to choose from the population

counts - Repeated elements can be specified one at a time or with the optional keyword-only counts parameter.

 

For example, sample(['red', 'blue'], counts=[4, 2], k=5) is equivalent to sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5).

 

Let’s try with an example.

 

sample_demo_1.py

 

import random

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]

primes_sample_4 = random.sample(primes, 4)

print('primes -> ', primes)
print('primes_sample_4 -> ', primes_sample_4)

 

Output

primes ->  [2, 3, 5, 7, 11, 13, 17, 19, 23]
primes_sample_4 ->  [2, 11, 17, 13]

 

Following example demonstrate the counts argument.

 

sample_demo_2.py

import random

my_list = ['red', 'blue']
sample_elements = random.sample(my_list, counts = [4, 2], k=5)

print('my_list -> ', my_list)
print('sample_elements -> ', sample_elements)

Output

my_list ->  ['red', 'blue']
sample_elements ->  ['blue', 'red', 'red', 'red', 'blue']




 

Previous                                                    Next                                                    Home

No comments:

Post a Comment