Randomly select elements from list without repetition in Python
Python’s built-in module in
random module is used to work with random data. The
random module provides various methods to select elements randomly from a list, tuple, set, string or a dictionary without any repetition. Below are some approaches which depict a random selection of elements from a list without repetition by:
Method 1: Using random.sample()
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
sample() method in the
random module. The
sample() is an inbuilt method of the random module which takes the sequence and number of selections as arguments and returns a particular length list of items chosen from the sequence i.e. list, tuple, string or set. It is used for random selection from a list of items without any replacement.
[50, 20, 10]
We can also use the
sample() method on a sequence of numbers, however, the number of selections should be greater than the size of the sequence.
[51, 50, 97, 22, 6]
Method 2: Using random.choices()
choices() method in the
random library, The
choices() method requires two arguments the list and k(number of selections) returns multiple random elements from the list with replacement. However, we need to convert the list into a set in order to avoid repetition of elements.
[30, 20, 40]
choices() method is applied on a sequence of unique numbers than it will return a list of unique random selections only if the
k argument (i.e number of selections) should be greater than the size of the list.
[46, 32, 85, 12, 68]
Method 3: Using random.choice()
choice() method in
random module, the
choice() method returns a single random item from a list, tuple, or string.
Below is program where
choice() method is used on a list of items.
Below is a program where choice method is used on sequence of numbers.