The random.sample() function in Python is a part of the random module which is used to generate a randomly selected sample of items from a given sequence/iterable object. This is one of the most common functions of the random module for generating random numbers. In this article, I will explain random.sample() function and using its syntax, parameters, and usage how we can get the specified list/sample of random items from a given iterable object/sequence with examples.
1. Quick Examples of random.sample() Function
Following is the quick examples of the usage of random.sample() function.
# Quick examples of random.sample() function.
import random
# Example 1: Generate random list using random.sample()
marks = [90,89,78,98,99]
print(“List:”, marks)
random_list = random.sample(marks, k=3)
# Example 2: Generate specified list of characters from string
# Initialize the string
string1 = “sparkby”
print(“String:”, string1)
random_list = random.sample(string1, k=3)
# Example 3: Pass counts param and generate specified length of sample
countries = [“USA”, “UK”, “China”]
random_list = random.sample(countries, counts=[10,20,15],k=12)
# Example 4: Pass Length of Sample Greater than Actual Sample
countries = [“USA”, “UK”, “China”]
print(random.sample(countries, counts=[10,20,15],k=50))
2. Random sample() in Python
Python random.sample() function is available in the random module, which will return the random items of a specified length from the iterable objects like list, string, tuple, set, etc. The random elements from the iterable objects are returned in a list.
2.1 Syntax of random.sample()
Following is the syntax of random.sample() function.
# Syntax of random.sample()
random.sample(sequence/iterable, counts, k)
2.2 Parameters
It takes three parameters.
sequence: Is the sequence/iterable in which random numbers are generated from this sequence/iterable.
counts: It is optional parameter which will represent the frequency of each element in the specified sequence/iterable. We need to pass the frequencies through a list.
k : It is the integer value that will specify the length of the sample. Its length must be less than or equal to the passed iterable object, other wise ValueError will be raised.
2.3 Return Value
It returns a randomly selected subset of numbers from a given sequence/iterable object.
3. Generate Random List using random.sample() Function
By using the Python radom.sample() function lets get the random values from the input List object. To get this pass the list as input to the sample() function along with the specified length(k). It selects the random values from the list and returns the result as a list.
# import random module
import random
# Initialize list
marks = [90,89,78,98,99]
print(“List:”, marks)
# Generate random list using random.sample()
random_list = random.sample(marks, k=3)
print(“Random list:”, random_list )
Yields below output.
4. Generate Random Characters from the String
Let’s initialize the string and pass it to the random.sample() function along with specified length(k) to get the random characters of a specified length from the String.
# Import
import random
# Initialize the string
string1 = “sparkby”
print(“String:”, string1)
# Generate specified list of characters from string
random_list = random.sample(string1, k=3)
print(“Random list:”, random_list )
Yields below output.
There are 7 characters in the original string, we specified the length of the random sample as 3, so it returned three characters from the string as a list[‘k’, ‘b’, ‘p’].
5. Using counts Param into random.sample()
If you wanted to generate random values from a list where the random count is larger than the input list, use the count param of the Python random.sample() to specify the frequency of the values. Let’s create a Python list of three countries (strings) and provide frequency 10 for “USA”, frequency 20 for “UK” and frequency 15 for “China” in the counts parameter and specify the sample length for 12 in the ‘k’ parameter.
import random
# Pass counts param and generate specified length of sample
countries = [“USA”, “UK”, “China”]
random_list = random.sample(countries, counts=[10,20,15],k=12)
print(“Random sample:n”, random_list)
Yields below output.
# Output:
Random sample:
[‘UK’, ‘China’, ‘China’, ‘UK’, ‘USA’, ‘China’, ‘UK’, ‘USA’, ‘China’, ‘China’, ‘UK’, ‘China’]
We can see that 12 countries have been generated in a sample.
6. Error Scenario
When the length of sample (k) is greater than the actual sample, It will return the ValueError.
import random
# Pass Length of Sample Greater than Actual Sample
countries = [“USA”, “UK”, “China”]
print(random.sample(countries, counts=[10,20,15],k=50))
Totally there are 45 elements. But we provided 50 to k. So the ValueError: Sample larger than population or is negative is raised.
7. Conclusion
In this article, I have explained random.sample() function in Python by using its syntax, parameters, and usage. Using this we can get the specified list/sample of random items from a given iterable object/sequence with examples. And also explained passing the length of the sample greater than the actual sample raises ValueError.
The random.sample() function in Python is a part of the random module which is used to generate a randomly selected sample of items from a given sequence/iterable object. This is one of the most common functions of the random module for generating random numbers. In this article, I will explain random.sample() function and using its Read More Python, Python Tutorial, Python Random