Generate Random Tuple from List with Probability in Python

By | November 29, 2024

Given a tuple list with probability, get a random tuple.

Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], prob_list = [0.4, 0.3, 0.1, 0.2]
Output : [(7, 6)]
Explanation : (7, 6) with probality 0.3 is extracted from result.

Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], prob_list = [0.4, 0.3, 0.1, 0.2]
Output : [(1, 0)]
Explanation : (1, 0) with probality 0.1 is extracted from result.

Method #1 : Using numpy.choice() + map() + str
In this all the tuples are converted to string as probabilty param required 1D elements to be as container elements. The choice(), extracts the random tuple accepting probability list as parameter. Needed numpy library to run this.

# Random tuple from Tuple List (with Probability)
# Using choice() + str + map
from numpy.random import choice

# initializing list
test_list = [(4, 5), (7, 6), (1, 0), (3, 4)]
             
# printing original list
print("The original list is : " + str(test_list))

# initializing Probability list 
prob_list = [0.4, 0.3, 0.1, 0.2]

# using choice() to get result 
res = choice(list(map(str, test_list)), p = prob_list)

# printing result
print("The random tuple : " + str(res))

Method #2 : Using random.choices() + weights param.
From python 3.6, choices() accepts “weights” parameter to perform task of getting random number with probability weights as parameter.

# Python3 code to demonstrate working of
# Random tuple from Tuple List (with Probability)
# Using random.choices() + weights param.
import random

# initializing list
test_list = [(4, 5), (7, 6), (1, 0), (3, 4)]
             
# printing original list
print("The original list is : " + str(test_list))

# initializing Probability list 
prob_list = [0.4, 0.3, 0.1, 0.2]

# using weights param to input Probabilities
res = random.choices(test_list, weights=prob_list)

# printing result
print("The random tuple : " + str(res))

Output

The original list is : [(4, 5), (7, 6), (1, 0), (3, 4)]
The random tuple : [(4, 5)]
Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.