The sample() function in the random module generates a unique random sample of elements from a sequence/population.
sample(seq, k = 5, counts = None)
copy
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.
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.
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.