Python random choices

Python random choices

Python random module : choices() 

In this article,we will see how to use random.choices() function.Python 3.6 introduced a new function choices() in the random module. By using random.choices() we can make a weighted random choice with replacement. You can also call it a weighted random sample with replacement.  

The choices() method returns a list with the randomly selected element from the specified sequence.You can weigh the possibility of each result with the weights parameter or the cum_weights parameter.The sequence can be a string, a range, a list, a tuple or any other kind of sequence.

Syntax :

random.choices(sequence, weights=None, cum_weights=None, k=1)

Parameter Values :

sequenceRequired. A sequence like a list, a tuple, a range of numbers etc.
weightsOptional. A list were you can weigh the possibility for each value.
Default None
cum_weightsOptional. A list were you can weigh the possibility for each value, only this time the possibility is accumulated.
Example: normal weights list: [2, 1, 1] is the same as this cum_weights list; [2, 3, 4].
Default None
kOptional. An integer defining the length of the returned list

Return Value :

Every time output will be different as the system returns random elements.

Note: You cannot specify both weights and cum_weights.

  • The random.choices() return a k sized list of elements chosen from the population with replacement.
  • weights or cum_weights are used to define the selection probability for each element.
  • If a weights sequence is specified, random selections are made according to the relative weights.
  • Alternatively, if a cum_weights sequence is given, the random selections are made according to the cumulative weights.

First, define the probability for each element. As mentioned above we can define weights sequence using the following two ways :-

  1. Relative weights
  2. Cumulative weights(cum_weights)

Relative weights to choose elements from the list with different probability :

If you specified the relative weight, the selections are made according to the relative weights. You can specify relative weights using weight parameter.

ExampleChoose 5 elements from the list with different probability

#importing random module
import random     

#use of weighted probability
numberList = [111222333444555]
print(random.choices(numberList, weights=(1020304050), k=5))    


  • As you can see in the output, we got 555 three times because we specified the highest weight for it. So it has the highest probability to be selected
  • We specified K=5 to choose 5 elements, you can specify any number you want. for example, to choose only 1 element you can specify k=1.
  • Weights sum is not 100 because they're relative weights, not percentages.

The weighted probability of selecting each element is determined by the following rule.

Probability = element_weight/ sum of all weights

In the above example, the probability of occurring each element is determined is as follows

The total weight is 10+20+30+40+50 = 150

List is [111, 222, 333, 444, 555]

It returns 111 with probability 10/150 = 0.06
It returns 222 with probability 20/150 = 0.13
It returns 333 with probability 30/150 = 0.20
It returns 444 with probability 40/150 = 0.26
It returns 555 with probability 50/150 = 0.33

Cumulative weights to choose elements from the list with different probability :

Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights. You can specify cumulative weights using the cum_weights parameter.

Note: Python converts the relative weights to cumulative weights before making selections. So, I suggest you pass cumulative weights to saves time and extra work

The cumulative weight of each element is determined by using the following formula.

cum_weight= Weight of previous element + own weight.

For example, the relative weights [5, 10, 15, 20] are equivalent to the cumulative weights [5, 15, 30, 50].

Example: Choose 4 elements from the list with different probability

 #importing random module
import random    

#use of cumulative weighted probability
nameList = ["Kelly""Scott""Emma""John"]
print(random.choices(nameList, cum_weights=(5153050), k=4))  


['John', 'Kelly', 'John', 'Scott']

Example: Choose a single element form list with different probability

 import random

List = ["Kelly""Scott""Emma""John"]
for i in range(5):
    print("Iteration:", i, "Random choice is ")
    x= random.choices(List, cum_weights=(5153050), k=1)


Iteration: 0 Random choice is 
Iteration: 1 Random choice is 
Iteration: 2 Random choice is 
Iteration: 3 Random choice is 
Iteration: 4 Random choice is 

As you can see we got John 3 times because it has the highest probability of being selected.

Points to remember before implementing weighted random choices :

  • If you don't specify the relative or cumulative weight, random.choices() will choose elements with equal probability.
  • The specified weights sequence must be of the same length as the population sequence.
  • Don't specify relative weights and cumulative weight at the same time to avoid Type Error.(TypeError: Cannot specify both weights and cumulative weights)
  • You can specify The weights or cum_weights only as integers, floats, and fractions but excludes decimals.
  • Weights must be non-negative.

  **********END OF ARTICLE********

More Articles of Vishal Lodhi:

Name Views Likes
Python string zfill 92 0
Python string swapcase 80 0
Python string title 84 0
Python string startswith 89 0
Python string replace 134 0
Python string translate 72 0
Python string rpartition 76 0
Python string partition 66 0
Python string splitlines 95 0
Python string rsplit 65 0
Python string split 65 0
Python string rindex 73 0
Python string rfind 93 0
Python string upper 68 0
Python string lower 67 0
Python string maketrans 75 0
Python string strip 72 0
Python string rstrip 75 0
Python string lstrip 71 0
Python string rjust 81 0
Python string ljust 81 0
Python string len 70 0
Python string join 63 0
Python string casefold 68 0
Python string isprintable 70 0
Python string encode 68 0
Python string isdecimal 73 0
Python string isidentifier 65 0
Python string isupper 62 0
Python string istitle 69 0
Python string isspace 82 0
Python string isnumeric 87 0
Python string isdigit 68 0
Python string islower 72 0
Python string isalpha 82 0
Python string isalnum 78 0
Python string index 78 0
Python string find 82 0
Python string expandtabs() 73 0
Python string endswith 77 0
Python string count 72 0
Python string capitalize 64 0
Python string center 74 0
Python string Introduction 89 0
Python string Template 128 0
Python string Formatter 122 0
Python string printable 169 0
Python string whitespace 124 0
Python string punctuation 84 0
Python string octdigits 75 0
Python string hexdigits 89 0
Python string digits 68 0
Python string ascii_letters 260 0
Python string ascii_lowercase 116 0
Python string ascii_uppercase 121 0
How to Create Download Manager in Python 393 0
Python random weibullvariate 150 0
python random paretovariate 121 0
Python random vonmisesvariate 151 0
Python random normalvariate 158 0
Python random lognormvariate 102 0
Python random gauss 104 0
Python random gammavariate 112 0
Python random expovariate 165 0
Python random betavariate 148 0
Python random triangular 103 0
Python random uniform 129 0
Python random random 108 0
Python random sample 160 0
Python random shuffle 168 0
Python random choices 189 0
Python random choice 151 0
Python random randint 134 0
Python random randrange 182 0
Python random getrandbits 127 0
Python random setstate 121 0
Python random getstate 160 0
Python random seed 158 1
Python random Introduction 158 0