How to select items randomly but weighted by probability with Python?

Sometimes, we want to select items randomly but weighted by probability with Python.

In this article, we’ll look at how to select items randomly but weighted by probability with Python.

How to select items randomly but weighted by probability with Python?

To select items randomly but weighted by probability with Python, we can call random.choice with the weights parameter set to the probability of each item being chosen.

For instance, we write:

import random

choices = random.choices(
  population=[['a','b'], ['b','a'], ['c','b']],
  weights=[0.2, 0.2, 0.6],
  k=10
)

print(choices)

We call random.choices with population set to the items that can be chosen.

weights has the probability of each item in population being chosen.

k is the number items to choose.

The items chosen are returned in a list and assigned to choices.

Therefore, choices is:

[['a', 'b'], ['c', 'b'], ['a', 'b'], ['c', 'b'], ['c', 'b'], ['c', 'b'], ['b', 'a'], ['a', 'b'], ['c', 'b'], ['a', 'b']]

Conclusion

To select items randomly but weighted by probably with Python, we can call random.choice with the weights parameter set to the probability of each item being chosen.