random
: sample() random.sample()
function to choose multiple items from a list, set, and dictionary. Python's random module provides random.sample()
function for random sampling and randomly pick more than one element from the list without repeating elements. The random.sample()
returns a list of unique elements chosen randomly from the list, sequence, or set, we call it random sampling without replacement.random.sample(sequence, k)
Parameter | Description |
---|---|
sequence | Required. A sequence. Can be any sequence: list, set, range etc. |
k | Required. The size of the returned list |
k length new list of elements chosen from the sequence.
random.sample()
function raises a type error if you miss any of the required arguments.# Python3 program to demonstrate# the use of sample() function .# import randomfrom random import sample# Prints list of random items of given lengthlist1 = [1, 2, 3, 4, 5]print(sample(list1,3))
Output :
[5, 4, 2]
2. Basic use of sample() function.
# Python3 program to demonstrate# the use of sample() function .# import randomimport random# Prints list of random items of# length 3 from the given list.list1 = [1, 2, 3, 4, 5, 6]print("With list:", random.sample(list1, 3))# Prints list of random items of# length 4 from the given string.string = "Cppsecrets"print("With string:", random.sample(string, 4))# Prints list of random items of# length 4 from the given tuple.tuple1 = ("vishal", "cpp", "computer", "science","portal", "secrets", "btech")print("With tuple:", random.sample(tuple1, 4))# Prints list of random items of# length 3 from the given set.set1 = {"c", "p", "p", "s", "e", "c", "r", "e", "t", "s"}print("With set:", random.sample(set1, 3))
Output:
Note: As you can see the random.sample()
function doesn't repeat the items in the result list. This is also called a random sample without replacement. If you want to generate random samples without replacement out of a list or population then you should use random.sample()
.
Important Note:
If your list itself contains repeated or duplicate elements, then random.sample()
can pick repeated items because each occurrence is a possible selection in the sample. I.e., The random.sample()
can pick the repeated items from the specified list if the unique members are less than a sampling size.
A sample function can raise the following two errors.
ValueError
If the sample size is larger than the population (i.e., list or set) sizeTypeError
if any of the two arguments is missing.Output:
Comments