Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Weighted Random Values In Python

This is how to weight the return value of a seleciton

Code

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)

Results

alfa
['charlie', 'charlie', 'charlie', 'charlie', 'bravo']

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