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.
import random
a = [10, 20, 30, 40, 50]
r = random.sample(a, 3)
print(r)
Output
[10, 20, 50]
Explanation: random.sample(a, 3) selects 3 unique elements from list a.
Syntax
random.sample(sequence, k)
Parameters:
- sequence: input sequence (list, tuple, string or range).
- k: Number of elements to select.
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.
import random
s = "python"
r = random.sample(s, 3)
print(r)
Output
['o', 'h', 'n']
Explanation: random.sample(s, 3) selects 3 characters from string s.
Example 2: This code selects random numbers from a range.
import random
r = random.sample(range(1, 11), 4)
print(r)
Output
[8, 2, 9, 6]
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.
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 <module>
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.