## 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 :

ParameterDescription
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 moduleimport random     #use of weighted probabilitynumberList = [111, 222, 333, 444, 555]print(random.choices(numberList, weights=(10, 20, 30, 40, 50), k=5))    `

Output:

[555222555222555]
• 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 = 150List is [111, 222, 333, 444, 555]It returns 111 with probability 10/150 = 0.06It returns 222 with probability 20/150 = 0.13It returns 333 with probability 30/150 = 0.20It returns 444 with probability 40/150 = 0.26It 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 moduleimport random    #use of cumulative weighted probabilitynameList = ["Kelly", "Scott", "Emma", "John"]print(random.choices(nameList, cum_weights=(5, 15, 30, 50), k=4))  `

Output:

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

### Example: Choose a single element form list with different probability

` import randomList = ["Kelly", "Scott", "Emma", "John"]for i in range(5):    print("Iteration:", i, "Random choice is ")    x= random.choices(List, cum_weights=(5, 15, 30, 50), k=1)    print(x[0])`

Output:

`Iteration: 0 Random choice is JohnIteration: 1 Random choice is JohnIteration: 2 Random choice is ScottIteration: 3 Random choice is ScottIteration: 4 Random choice is Emma`

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 137 0
Python string swapcase 108 0
Python string title 109 0
Python string startswith 118 0
Python string replace 159 0
Python string translate 99 0
Python string rpartition 96 0
Python string partition 92 0
Python string splitlines 138 0
Python string rsplit 90 0
Python string split 90 0
Python string rindex 99 0
Python string rfind 121 0
Python string upper 95 0
Python string lower 97 0
Python string maketrans 104 0
Python string strip 95 0
Python string rstrip 115 0
Python string lstrip 96 0
Python string rjust 114 0
Python string ljust 113 0
Python string len 97 0
Python string join 92 0
Python string casefold 97 0
Python string isprintable 102 0
Python string encode 95 0
Python string isdecimal 101 0
Python string isidentifier 93 0
Python string isupper 96 0
Python string istitle 94 0
Python string isspace 115 0
Python string isnumeric 118 0
Python string isdigit 99 0
Python string islower 100 0
Python string isalpha 115 0
Python string isalnum 114 0
Python string index 103 0
Python string find 109 0
Python string expandtabs() 91 0
Python string endswith 109 0
Python string count 105 0
Python string capitalize 92 0
Python string center 96 0
Python string Introduction 115 0
Python string Template 160 0
Python string Formatter 169 0
Python string printable 246 0
Python string whitespace 163 0
Python string punctuation 119 0
Python string octdigits 104 0
Python string hexdigits 125 0
Python string digits 91 0
Python string ascii_letters 426 0
Python string ascii_lowercase 204 0
Python string ascii_uppercase 198 0
Python random weibullvariate 185 0
python random paretovariate 151 0
Python random vonmisesvariate 198 0
Python random normalvariate 228 0
Python random lognormvariate 134 0
Python random gauss 142 0
Python random gammavariate 158 0
Python random expovariate 232 0
Python random betavariate 235 0
Python random triangular 128 0
Python random uniform 165 0
Python random random 129 0
Python random sample 213 0
Python random shuffle 198 0
Python random choices 278 0
Python random choice 180 0
Python random randint 165 0
Python random randrange 259 0
Python random getrandbits 167 0
Python random setstate 162 0
Python random getstate 207 0
Python random seed 185 1
Python random Introduction 193 0