What is random.sample() in Python?

The random module

The random module in Python provides many options to generate random objects or numbers.

The sample() method in Python

The sample() function is used to create a random sample without replacement of a specified length, meaning that different objects will be selected from a sequence, but once an object has been selected, it will not be selected again.

If the sample contains repeating objects, each instance of that object is a valid selection choice.

Syntax


random.sample(population, k)

Arguments

  1. population: the sequence (such as a list or tuple) from which the random sample will be generated.

  2. k: the length of the list that contains the random sample that is generated. The value of k must be an int value equal to or less than the length of population.

Return value

The function returns a list of length k containing values selected from population.

If k is larger than the length of population, ValueError is raised.

Code

# first import random module
import random
# declaring list
testList = ["zero", "one", "two", "three", "four"]
randomSampleList = random.sample(testList, 3)
print("Random sample with list as population:", randomSampleList)
testStr = "Educative"
randomSampleStr = random.sample(testStr, 5)
print("Random sample with string as population:", randomSampleStr)
testTuple = ("C++", 123, "Python", 456)
print("Since k > len(tuple1), ValueError is raised: ")
random.sample(testTuple, 5)

Note: the output will be different every time the code is executed.

Free Resources