Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Get Weighted Random Choice in Python?
Python's weighted random choice allows you to select items from a list where each item has a different probability of being chosen. Unlike simple random selection where each item has equal chances, weighted selection lets you control the likelihood of each item being picked.
Syntax
The primary method for weighted random choice in Python is random.choices():
random.choices(population, weights=None, cum_weights=None, k=1)
Parameters:
population The list of items to choose from (required)
weights List of weights corresponding to each item (optional)
cum_weights List of cumulative weights (optional)
k Number of items to select (default is 1)
Using random.choices()
The most straightforward approach uses Python's built-in random.choices() function with explicit weights:
import random colors = ['Red', 'Blue', 'Green'] weights = [0.6, 0.3, 0.1] # 60%, 30%, 10% probability chosen = random.choices(colors, weights, k=5) print(chosen)
['Red', 'Red', 'Blue', 'Red', 'Red']
In this example, 'Red' has the highest weight (0.6), so it appears more frequently in the results.
Using numpy.random.choice()
NumPy provides an alternative approach with numpy.random.choice():
import numpy as np colors = ['Red', 'Blue', 'Green'] weights = [0.6, 0.3, 0.1] chosen = np.random.choice(colors, size=5, p=weights) print(chosen)
['Red' 'Red' 'Green' 'Red' 'Blue']
Note that NumPy uses the parameter p for probabilities and size instead of k.
Using Cumulative Weights
Instead of individual weights, you can use cumulative weights:
import random items = ['A', 'B', 'C', 'D'] cum_weights = [10, 30, 60, 100] # Cumulative weights result = random.choices(items, cum_weights=cum_weights, k=8) print(result)
['D', 'C', 'D', 'B', 'D', 'C', 'D', 'C']
Comparison
| Method | Library | Weight Parameter | Count Parameter | Return Type |
|---|---|---|---|---|
random.choices() |
Built-in | weights |
k |
List |
numpy.random.choice() |
NumPy | p |
size |
NumPy array |
Conclusion
Python offers multiple ways to perform weighted random selection. Use random.choices() for simple cases with built-in functionality, or numpy.random.choice() when working with NumPy arrays and scientific computing.
