Python random.sample() Function

Python random.sample() function is used to randomly select a specified number of elements from a sequence like a list, tuple, or string, or from a set.

Syntax

random.sample(sequence, k)

Parameters

  1. sequence (required): It can be any sequence, such as a list, set, dictionary, tuple, or string from which we can select a k-length number.
  2. k: The number of random elements you want to select from the sequence. It must be less than the size of the specified list.

Return Value

It returns the new list containing randomly selected elements.

Visual representation

Visual representation of Python random.sample() function

Example 1: Basic usage

import random

main_list = [21, 19, 18, 46, 29]

print("Choosing 3 random elements from the list using random.sample() function")

sampled_output = random.sample(main_list, 3)

print(sampled_output)

Output

Choosing 3 random elements from the list using random.sample() function

[29, 46, 19]

Example 2:  Raising Exception

Visual representation of ValueError - Sample larger than population or is negative

If you pass a sample larger than the population or is negative, it will throw an error.

import random

main_list = [21, 19, 18, 46, 29]

print("Choosing 6 random elements from the list using random.sample() function")

sampled_output = random.sample(main_list, 6)

print(sampled_output)

Output

ValueError: Sample larger than population or is negative

It might raise the following two errors.

  1. ValueError If the sample size is larger than the population (i.e., list or set) size.
  2. TypeError if any of the two arguments is missing.

Example 3: Specifying “counts” parameter

Visual representation of Specifying counts parameter

This function provides the ability to sample a specified number of unique items from a population (like a list). 

import random

main_list = [11, 21, 19]

random_list = random.sample(main_list, counts=[10, 20, 15], k=12)

print("Random sample:\n", random_list)

Output

Random sample:

[21, 11, 11, 11, 11, 11, 19, 21, 19, 21, 21, 19]

Example 4: Generating random characters from the string

import random


def generate_random_chars_using_sample(s, n):
  """Generate n random characters from string s using random.sample()."""
  if n > len(s):
    raise ValueError(
       "n should be less than or equal to the length of the string")
  return ''.join(random.sample(s, n))


string = "abcdefghijklmnopqrstuvwxyz"
num_chars = 5

random_chars = generate_random_chars_using_sample(string, num_chars)
print(random_chars)

Output

xwbrc

That’s it.

Related posts

Python random seed()

Python random choice()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.