Python random.sample() vs random.choice():
The Python random module provides a couple of useful functions. The random.sample() and random.choice() are used to get a list or a single random element from a given list. In this post, I will show you how these methods works with examples.
Python random.sample():
The sample() method is used to get a list of unique elements from a given list of elements. This method is mainly used for random sampling of data with no replacement.
It is defined as below:
random.sample(data, k, *, counts=None)
- data is the given sequence.
- It will pick a list of k unique elements.
- It returns a new list without modifying the original data list.
- counts is an optional parameter to define the repeated elements in the given list.
It raises a ValueError if the sample size is greater than the original list size.
Let’s take a look at the below example:
import random
given_list = list(range(20))
random_sample = random.sample(given_list, 5)
print(random_sample)
In the above example, we created a list of numbers given_list and called random.sample on this list to get a list of random 5 numbers.
Each time you run this program, it will print a list holding random elements.
Let me show you how to use counts:
import random
given_list = [2, 3]
random_sample = random.sample(given_list, 5, counts=[3, 3])
print(random_sample)
Here, the list given_list holds only two elements. But counts=[3,3] will define that both elements will repeat for 3 times. It is equivalent to random.sample([2, 2, 2, 3, 3, 3], 5). It will print output something as below:
[2, 3, 3, 3, 2]
Python random.choice():
The random.choice() function is used to get a single random element from a sequence. It is defined as:
random.choice(seq)
It takes one sequence seq as its parameter and returns one random element from this sequence.
It raises IndexError if the sequence seq is empty.
For example:
import random
random_choice = random.choice(range(100))
print(random_choice)
Output:
➜ python3 example.py
90
➜ python3 example.py
93
You might also like:
- Python string endswith method explanation with example
- Python string isalnum method explanation with example
- Python string isalpha method explanation with example
- Python string isdecimal method explanation with example
- Python string isdigit() method explanation with example
- Python string isidentifier() method
- Python string islower method explanation with example
- Python program to check if a number is divisible by another number or not
- Python program to check if a number is duck number or not