random.sample() vs random.choice() in Python

Here in this tutorial, we will learn about the difference between random.sample() and random.choice() functions.

The random module is used to shuffle values, generate some random data, etc and to do so first of all we need to import the random module from the standard Python library.

random.sample()

The sample() function in Python ensures that there are no duplicates out of all the values selected randomly.

import random

List = list(range(1,10))

result = random.sample(List, k=5)

print(result)

Output:

[2, 9, 7, 6, 1]

In the code written above, we have made a list containing numbers from 1-10 excluding 10.

Then we used the sample() function to get 5 distinct values each time and printed the result for the same.

random.choice()

The choice() function is used to select a random value from any type of sequence let it be a list, set, tuple, string, etc.

import random

List = list(range(1,10))

result = random.choice(List)

print(result)

Output:

4

In the above code, we have used the choice() function to get a random number chosen from the selected sequence which here is a list of numbers.

Also read: Random sampling from a list in Python

So the main difference between random.sample() and random.choice() is:

  • sample() function gives us a specified number of distinct results whereas the choice() function gives us a single value out of the given sequence.

We have seen the difference between random.sample() and random.choice() in Python.

 

Leave a Reply

Your email address will not be published.