random.sample() function Python (original) (raw)

Last Updated : 16 Feb, 2026

random.sample() function is used to select a specified number of unique elements from a sequence such as a list, tuple, string or range. It returns the selected elements as a new list. The selection is done without replacement, which means the same element will not appear more than once in the result.

**Example: This code selects 3 unique elements from a list using random.sample() and prints them.

Python `

import random a = [10, 20, 30, 40, 50] r = random.sample(a, 3) print(r)

`

**Explanation: random.sample(a, 3) selects 3 unique elements from list a.

Syntax

random.sample(sequence, k)

**Parameters:

**Returns: Returns a new list containing k randomly selected unique elements.

Examples

**Example 1: This code selects random characters from a string and returns them in a list.

Python `

import random s = "python" r = random.sample(s, 3) print(r)

`

**Explanation: random.sample(s, 3) selects 3 characters from string s.

**Example 2: This code selects random numbers from a range.

Python `

import random r = random.sample(range(1, 11), 4) print(r)

`

**Explanation: random.sample(range(1, 11), 4) selects 4 numbers from range.

**Example 3: This code tries to select more elements than present, which raises an error.

Python `

import random a = [1, 2, 3] r = random.sample(a, 5) print(r)

`

**Output

Traceback (most recent call last):
File "c:\Users\gfg0753\test.py", line 3, in
r = random.sample(a, 5)
File "C:\Users\gfg0753\AppData\Local\Programs\Python\Python313\Lib\random.py", line 434, in sample
raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative

**Explanation: random.sample(a, 5) gives error because k is greater than list size.