home ~ projects ~ socials

Weighted Random Values In Python

This is how to weight the return value of a seleciton

import random

items = ['alfa', 'bravo', 'charlie', 'delta']
weights = [10, 20, 60, 10]

single_item = random.choices(items, weights, k=1)[0]
print(single_item)

weighted_list = random.choices(items, weights, k=5)
print(weighted_list)
Output:
alfa
['charlie', 'charlie', 'charlie', 'charlie', 'bravo']

The k=1 says to return only one item in the list and the [0] returns it directly

-- end of line --