random.sample() function Python (original) (raw)
Last Updated : 29 Apr, 2025
**sample() is an built-in function of **random module in Python that returns a particular length list of items chosen from the sequence i.e. list, tuple, string or set. Used for random sampling without replacement. **Example:
Python `
from random import sample
a = [1, 2, 3, 4, 5] print(sample(a,3))
`
**Explanation: This code uses the **sample() method to randomly select 3 unique elements from the list **a = [1, 2, 3, 4, 5]. The selected elements are printed as a new list.
Syntax
random.sample(sequence, k)
**Parameters:
- **sequence: Can be a list, tuple, string, or set.
- **k: An Integer value, it specify the length of a sample.
**Returns: k length new list of elements chosen from the sequence.
Examples of random.sample() function
Example 1: Basic use of sample() function
The code demonstrates how to use random.sample() with different types of sequences:
Python `
import random
a = [1, 2, 3, 4, 5, 6] print("With list:", random.sample(a, 3))
s = "GeeksforGeeks" print("With string:", random.sample(s, 4))
t = ("ankit", "geeks", "computer", "science", "portal", "scientist", "btech") print("With tuple:", random.sample(t, 4))
b = {"a", "b", "c", "d", "e"} print("With set:", random.sample(list(b), 3))
`
Output
With list: [3, 4, 5] With string: ['r', 'k', 'f', 'e'] With tuple: ['btech', 'scientist', 'portal', 'science'] With set: ['b', 'a', 'e']
**Explanation:
- **List: It randomly selects 3 elements from the list **a.
- **String: It randomly selects 4 characters from the string **s.
- **Tuple: It randomly selects 4 elements from the tuple **t.
- **Set: Since **random.sample() does not directly work with sets, the set **b is converted into a list, and 3 random elements are selected.
Example 2: Sampling More Elements Than Available in List
This code demonstrates the behavior of **random.sample() when we try to sample more elements than are present in the list, which will result in a **ValueError.
Python `
import random
a = [1, 2, 3, 4] print(random.sample(a, 5))
`
**Output:
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 4, in
print(random.sample(a, 5))
~~~~~~~~~~~~~^^^^^^
File "/usr/local/lib/python3.13/random.py", line 434, in sample
raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative