random
moduleThe random
module in Python provides many options to generate random objects or numbers.
sample()
method in PythonThe 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.
random.sample(population, k)
population
: the sequence (such as a list or tuple) from which the random sample will be generated.
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
.
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.
# first import random moduleimport random# declaring listtestList = ["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.