Get n Random items from a List in Python
In this article, you will know how to get n random items in a list through Python. A pre-defined method named random is used to get n random items from a list in Python.
About Random Module:
Random module is one of the predefined Modules in Python, as a result there methods return random values.
For integers it uniformly select from range. For sequences it uniform selection for the random element, a function to generate a random permutation of a list in-place, and a function to generate a random sampling without replacement. Lets have a look at importing the Random Module
Importing Random Module:
In Python random module consists of various inbuilt Methods. Some of them used in this article are
- choice() to randomly select an item from list, tuple etc.
- sample() to select multiple values as per our requirement.
Approach – 1: Using choice() Method
random.choice() returns a random number from given sequence. Where, Sequence can be a list, tuple etc. It returns single value from available data that consider duplicate values in the sequence(list).
- It consider duplicate values in sequence.
Syntax for choice() Method:
Here, choice is method in Random Module. Whereas, sequence can be a list, tuple, set etc. It returns a random element from the given Sequence. Lets have a look at the following example to illustrate the working of chioce() method.
import random print(random.choice([1,2,3]))
The output of the above code will be as follows:
From the above, System had selected the random number ‘3’ from a list [1,2,3].
Since, choice() Method returns a single Element, we have use it in Looping Statements (i.e. for, while etc.) to generate n Random Elements. Lets have a glance over the following example.
import random n=int(input("Enter n Value :")) l=[1,2,3,2,2,1] for i in range(n): print(random.choice(l))
The Input for the above program will be as follows
Enter n Value : 4
Hence, the corresponding output will be as follows
2 1 3 2
Now, lets have a glance over the 2nd Approach of generating n random elements using sample() Method.
Approach – 2: Using sample() Method
random.sample() Method is used to return required list of items from sequence. It does’t allow duplicate elements in sequence.
Its the only difference between choice() and sample() methods.
Syntax for sample() Method:
- ‘k’ is parameter of new list for values selected by user from sequence(list).
Lets have a look at the following Example of Python Code using sample() Method.
import random l=[1,2,2,2,4,4] n=int(input()) print(random.sample(l,n))
The input for the above code will be as follows
3 # The Value of n
Hence, the corresponding Output will be as follows
Using the sample() method is better than choice() because it returns multiple values. Above all programs are some of methods to implement n random numbers generation from a given list.
Also, read: Random Elements from a Tuple