Choose element(s) from List with different probability in Python
Last Updated :
11 Oct, 2020
Have you ever wondered how to select random elements from a list with different probability in Python? In this article, we will discuss how to do the same. Let’s first consider the below example.
Python3
import random
sam_Lst = [ 10 , 20 , 3 , 4 , 100 ]
ran = random.choice(sam_Lst)
print (ran)
|
In the above example, the probability of getting any element from the list is equal. But we want such methods in which the probability of choosing one element from the list is different. This is known as the weighted random choice in Python. In order to find weighted random choices in Python, there exist two ways:
- Relative weights
- Cumulative weights
The function which will help us in this situation is random.choices(). This function allows making weighted random choices in python with replacement.
Syntax:
random.choices(population, weights=None, *, cum_weights=None, k=1)
Here, the ‘weight’ parameter plays an important role.
Case 1: Using Relative weights
The weight assigned to an element is known as relative weight.
Example 1:
Python3
import random
num_lst = [ 1 , 22 , 43 , 19 , 13 , 29 ]
print (random.choices(num_lst, weights = (
14 , 25 , 30 , 45 , 55 , 10 ), k = 6 ))
|
Output:
[19, 19, 13, 22, 13, 13]
In the above example, we assign weights to every element of the list. The weight of the element ‘13′ is highest i.e 55, so the probability of its occurrence is maximum. As we can see in the output, element 13 occurs 3 times, 19 occurs 2 times, and so on. So, now the probability of choosing an element from the list is different.
Example 2:
Python3
import random
name_lst = [ 'October' , 'November' , 'December' ,
'January' , 'March' , 'June' ]
print (random.choices(name_lst, weights = (
40 , 25 , 30 , 5 , 15 , 80 ), k = 3 ))
|
Output:
['June', 'October', 'June']
In the above example, the weight of element ‘June’ is maximum so its probability of selection will be maximum. And here, k=3 which means we are choosing only the top 3 elements from the list.
Example 3:
Python3
import random
name_lst = [ 'Fit' , 'Infected' , 'Recovered' , 'Danger' ]
for i in range ( 6 ):
print ( "Random choice" , i + 1 )
randomele = random.choices(name_lst, weights = (
50 , 80 , 10 , 5 ), k = 1 )
print (randomele[ 0 ])
|
Output:
Random choice 1
Recovered
Random choice 2
Danger
Random choice 3
Infected
Random choice 4
Infected
Random choice 5
Infected
Random choice 6
Fit
In the above example, we use FOR loop to choose an element from a list with a different probability.
Case 2: Using Cumulative weights
The cumulative weight of an element is determined by adding the weight of its previous element and its own weight.
Example 1:
Python3
import random
num_lst = [ 1 , 22 , 93 , 19 , 13 , 25 ]
print (random.choices(num_lst, cum_weights = (
7 , 13 , 15 , 20 , 25 , 20 ), k = 6 ))
|
Output:
[1, 22, 93, 22, 19, 1]
In the above example, the cumulative weight of element ‘19′ is maximum, so the probability of its selection will also be maximum.
Example 2:
Python3
import random
name_lst = [ 'October' , 'November' , 'December' ,
'January' , 'March' , 'June' ]
print (random.choices(name_lst, cum_weights = (
40 , 20 , 3 , 7 , 15 , 15 ), k = 3 ))
|
Output:
['January', 'March', 'January']
In the above example, we choose k=3 so we get the top 3 elements that have the maximum probability of selection.
Example 3:
Python3
import random
name_lst = [ 'October' , 'November' , 'December' ,
'January' , 'March' , 'June' ]
for i in range ( 6 ):
print ( "Random choice" , i + 1 )
randomele = random.choices(name_lst, cum_weights = (
7 , 13 , 15 , 20 , 25 , 20 ), k = 1 )
print (randomele[ 0 ])
|
Output:
Random choice 1
November
Random choice 2
January
Random choice 3
October
Random choice 4
December
Random choice 5
November
Random choice 6
January
In the above example, we use FOR loop to choose an element from a list with a different probability.
Note: The value of k depends on the users, and since its relative weight so the total sum of weights can exceed 100.
Similar Reads
How to choose elements from the list with different probability using NumPy?
We will see How to use numpy.random.choice() method to choose elements from the list with different probability. Syntax: numpy.random.choice(a, size=None, replace=True, p=None) Output: Return the numpy array of random samples. Note: parameter p is probabilities associated with each entry in a(1d-arr
2 min read
Randomly select elements from list without repetition in Python
We are given a list, and our task is to randomly select elements from it without repetition. This means that once an element is selected, it should not be picked again. For example, given a = [10, 20, 30, 40, 50], selecting three elements randomly could result in [30, 10, 50], but the same element s
2 min read
Iterate over Two Lists with Different Lengths in Python
Iterating over two lists of different lengths is a common scenario in Python. However, we may face challenges when one list is shorter than the other. Fortunately, Python offers several methods to handle such cases, ensuring that our code is both readable and efficient. Using zip() function - Loop u
3 min read
How To Find Probability Distribution in Python
A probability Distribution represents the predicted outcomes of various values for a given data. Probability distributions occur in a variety of forms and sizes, each with its own set of characteristics such as mean, median, mode, skewness, standard deviation, kurtosis, etc. Probability distribution
3 min read
Randomly Select N Elements from List in Python
When working with lists in Python, we often need to randomly select a specific number of elements. For example, consider the list a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]. We might want to randomly select 3 elements from this list. Let's discuss different ways for selecting n random elements fr
3 min read
Python - Find all elements count in list
In Python, counting the occurrences of all elements in a list is to determine how many times each unique element appears in the list. In this article, we will explore different methods to achieve this. The collections.Counter class is specifically designed for counting hashable objects. It provides
3 min read
How to Create a List of N-Lists in Python
In Python, we can have a list of many different kinds, including strings, numbers, and more. Python also allows us to create a nested list, often known as a two-dimensional list, which is a list within a list. Here we will cover different approaches to creating a list of n-lists in Python. The diffe
3 min read
Using Else Conditional Statement With For loop in Python
Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while
2 min read
Filter Python list by Predicate in Python
A predicate is a function that returns either True or False for a given input. By applying this predicate to each element of a list, we can create a new list containing only the elements that satisfy the condition. Let's explore different methods to filter a list based on a predicate. Using list com
3 min read
Python Counter | Majority Element
Majority Element: A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element). Write a function which takes an array and emits the majority element (if it exists), otherwise prints NONE as follows: Examples: Input : 3 3 4
2 min read