Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python random.sample() Method



The random.sample() method in Python used for generating random samples from a sequence without replacement. It allows you to generate a list of unique elements randomly chosen from a given sequence such as lists, tuples, strings, or ranges. This method is especially useful when you need to ensure that each selected element is unique and not repeated within the sample. This is particularly useful for tasks that require random sampling, such as statistical analysis, simulations, and random selection processes and other applications.

It's important to note that if the given sample size exceeds the sequence size/length, this method will raise a ValueError.

Syntax

Following is the syntax of sample() method −

random.sample(seq, k, *, counts=None)

Parameters

The Python random.sample() method accepts the below parameter −

  • seq: A sequence data type, can be any iterable such as a list, tuple, string, or range.

  • k: length of the output list, whose elements are chosen from the seq.

  • counts: An optional keyword-only parameter that allows specifying the frequency of each element in the population.

Return Value

This random.sample() method returns a list of k unique elements chosen randomly from the given sequence.

Let's consider examples using any sequential data type such as a list, string, tuple, or set to randomly select unique elements from the sequence.

Example 1

Let us see an example of random.sample() method for a list data type and mentioning the output list size as 3.

from random import sample

list=[10,20,30,40,50]
sample_list=sample(list,3)
print(sample_list)

Following is the output −

[30, 20, 10]

Note: The Output generated will be different for every execution as it returns a random item.

Example 2

Let us see an example of random.sample() method for a string data type.

from random import sample

str="Tutorialspoint"
sample_str=sample(str,3)
print(sample_str)

While executing the above code you will get the similar output like below −

['i', 'n', 't']

Example 3

Now, let us see an example of random.sample() method for a tuple data type.

from random import sample

tuple=("Tutorialspoint", "Ankit","Tutorix","courses","online")
sample_tuple=sample(tuple,3)
print(sample_tuple)

The output of the above code is as follows −

['Tutorialspoint', 'courses', 'Tutorix']

Example 4

Here is an example of using the random.sample() method with a set data type.

from random import sample

set=("a","b","c","d","e")
sample_set=sample(set,3)
print(sample_set)

When we run above program, it produces similar results like below −

['e', 'a', 'd']

Example 5

This example demonstrates error handling using Python's try and except blocks with the random.sample() method.

import random

# List of elements
my_list = [1, 2, 3, 1, 3, 2]

# Try to generate a sample of 10 elements from the list
try:
    sampled_list = random.sample(my_list, 10)
except ValueError as e:
    print("Error:", e) 

Following is the output −

Error: Sample larger than population or is negative
python_modules.htm
Advertisements