Use the sample()
Function
#import the random module
import random
#The sequence to sample
my_seq = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#get a sample of 4 elements
print(random.sample(my_seq, 4))
The sample() function in the random module generates a unique random sample of elements from a sequence/population.
sample(seq, k = 5, counts = None)
seq |
Required. A sequence of objects like lists, tuples, strings, etc, from which to draw the samples |
k |
Required. An integer that indicates the length of the sample to draw from the population. |
counts |
Optional. Specifies the number of times each item in the sequence should be sampled |
The function returns a list containing k
random and unique elements drawn from the sequence. The original sequence remains unchanged.
Get a sample of elements from a population of integers between 0 and 100
#import the random module
import random
data = range(100)
sample = random.sample(data, 10)
print(sample)
with a tuple
#import the random module
import random
data = (0.1, 0.4, 0.2, 0.3, 0.0, 0.5, 0.2, 0.4, 0.1)
sample = random.sample(data, 3)
print(sample)
The k argument should always be positive and smaller than the total number of elements in the original sequence. Otherwise, a ValueError
will be raised.
A ValueError
is raised if k is greater than the length of the original sequence
#import the random module
import random
data = [1, 2, 3]
#Raises an erro because the defaultk is greater than the length of the sequence
sample = random.sample(data, 5)
print(sample)
You should also note that sets and dictionaries are not sequences, since their elements are unordered. We should first cast such types into a sequence type such as a list or a tuple before sampling their elements. Passing non-sequence objects will result in an error being raised.
import random
data = {0, 1, 2, 3, 4, 5, 6, 7}
sample = random.sample(data, 3)
print(sample)
First cast set elements to a list before sampling them
import random
data = {0, 1, 2, 3, 4, 5, 6, 7}
#cast the set to a list
data = list(data)
sample = random.sample(data, 3)
print(sample)