Python Random sample() Method

Python Random sample() method is used to randomly select a specified number of items from a sequence such as a list, tuple, or string, or from a set.

Visual representation of Passing a List to random.sample() method

Syntax

random.sample(sequence, k)

Parameters

  1. sequence (required): The source sequence (like a list, tuple, or set) from which you want to select items.
  2. k(required): The number of items you want to randomly select. The k value cannot be larger than the size of the sequence. If it is, the method will raise a ValueError.

Return Value

It returns the new list containing randomly selected elements.

Example 1: Using with a List

import random

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

print("Choosing 3 random elements)

sampled_output = random.sample(main_list, 3)

print("Choosing 3 random elements: ",sampled_output)

Output

Choosing 3 random elements: [29, 46, 19]

Each time you run this code, you may get a different combination of items.

Example 2: k value larger then the sequence

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

import random

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

sampled_output = random.sample(main_list, 6)

print("Choosing 3 random elements: ",sampled_output)

Output

ValueError: Sample larger than population or is negative

Example 3: Using with a String

Using with a String

import random

main_str = "California"

print(random.sample(main_str, 2))

Output

['r', 'f']

Example 4: Using with a Tuple

Using with a Tuple

import random

main_tuple = ("red", "blue", "green", "yellow", "purple")

print(random.sample(main_tuple, 4))

Output

['purple', 'green', 'yellow', 'blue']

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.