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.
Syntax
random.sample(sequence, k)
Parameters
- sequence (required): The source sequence (like a list, tuple, or set) from which you want to select items.
- 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
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
import random
main_str = "California"
print(random.sample(main_str, 2))
Output
['r', 'f']
Example 4: 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
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.