In this article, we will discuss how to randomly select n elements from the list in Python. Before moving on to the approaches let’s discuss Random Module which we are going to use in our approaches.
A random module returns random values. It is useful when we want to generate random values. Some of the methods of Random module are:- seed(), getstate(), choice(), sample() etc.
Select randomly n elements from a list using randrange()
Here, we are using the random randrange() function to return a single random number from a list.
Python3
import random
list = [1, 2, 3, 4]
get_index = random.randrange(len(letters))
print(letters[get_index])
|
Output:
3
Time Complexity: O(n) where n is the number of elements in the list
Auxiliary Space: O(1), here constant extra space is required
Selecting more than one random element from a list using sample()
The sample() method is used to return the required list of items from a given sequence. This method does not allow duplicate elements in a sequence.
python3
import random
list = [2, 2, 4, 6, 6, 8]
n = 4
print(random.sample(list, n))
|
Output:
[8, 6, 6, 4]
Selecting more than one random element from a list using choices()
Here, we are using the random choices() function to return more than one random number from a list.
Python3
import random
list = ['a', 'b', 'c', 'd', 'e', 'f']
n = 4
print(random.choices(list, k=n))
|
Output:
['d', 'd', 'f', 'a']
Select randomly n elements from a list using choice()
The choice() method is used to return a random number from given sequence. The sequence can be a list or a tuple. This returns a single value from available data that considers duplicate values in the sequence(list).
python3
import random
list = [2, 2, 4, 6, 6, 8]
n = 4
for i in range(n):
print(random.choice(list), end = " ")
|
Output :
8 2 4 6
RECOMMENDED ARTICLES – Randomly select elements from list without repetition in Python
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
14 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...