Skip to content
Related Articles

Related Articles

Improve Article

Randomly select n elements from list in Python

  • Last Updated : 21 Aug, 2020

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.
Random Module:
Random module is the predefined Module in Python, It contains methods to return random values. This module is useful when we want to generate random values. Some of the methods of Random module are:-
seed(), getstate(), choice(), sample() etc.

Let’s discuss different approaches to implement this.
Approach 1 : Using sample() Method. sample() method is used to return required list of items from a given sequence. This method do not allow duplicate elements in a sequence.




# importing random module
import random
  
# declaring list
list = [2, 2, 4, 6, 6, 8]
  
# initializing the value of n
n = 4
  
# printing n elements from list
print(random.sample(list, n))

Output :

[8, 6, 6, 4]

Approach 2 : Using choice() Method. 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).




# importing random module
import random
  
# declaring list
list = [2, 2, 4, 6, 6, 8]
  
# initializing the value of n
n = 4
  
# traversing and printing random elements
for i in range(n):
      
    # end = " " so that we get output in single line
    print(random.choice(list), end = " ")

Output :

8 2 4 6 

 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




My Personal Notes arrow_drop_up
Recommended Articles
Page :