The choices()
function in the random module generates a list of random elements from a given sequence, with the possibility of duplicate elements.
choices(seq, weight = None, cum_weight = None, k = 1)
seq |
Required. This is the sequence from which the items will be chosen from. |
weight |
Optional. Specifies the weight of each item in the sequence. It can be a list of weights that correspond to the items in the sequence or a single weight for all items. |
cum_weight |
Optional. Specifies a cumulative weight for each item in the sequence. Useful for creating a “bias” in the selection by making certain items more likely to be chosen than others. |
k |
Optional. Specifies how many items to select from the sequence. defaults to 1. |
The function returns a list containing k
random elements chosen from the sequence with respect to the weights.Please note that sets and dictionaries are not sequences since the items are unordered, they, therefore, cannot be used as arguments to the choices()
function, doing so will raise an error.
In the above example, we did not specify the number of elements to be chosen, therefore, 1 element(the default ) is chosen.