Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
random
random.sample()
communitycreator

What is random.sample() in Python?

Sarah Tanveer

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

python
random
random.sample()
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring