What is the random.choices() method in Python?
Overview
The choices() method of the random module is used randomly select elements from a population with replacement. The population supplied to the method should not be empty. This method also allows us to specify the weight given to the possibility of randomly selecting every value. The given weights can also be cumulative weights. If no weights are given, then the selections are made with equal probability. The method throws an error if all the values in the weights list are zero.
Method signature
choices(population, weights=None, *, cum_weights=None, k=1)
Parameters
population: This is a mandatory parameter that can be alist,tuple, orstring. It indicates the population from which random values will be picked.weights: This parameter is an optional numeric type that indicates the relative weights for the randomly chosen elements from the population.cum_weights: This parameter is an optional numeric type that indicates the cumulative weights for the randomly chosen elements from the population.k: This parameter indicates the number of random values to pick from the population.
Note: The
weightsandcum_weightsmust be the same length as the population sequence. Specifyingweightsandcum_weightsthrows an error.
Return value
This method returns random values chosen from the population.
Example
import randomdef pick_from_string_population():string = "edpresso"k = 5random_vals = random.choices(string, [5, 5, 3, 3, 2, 1, 4, 6], k=k)print("Using string as population")print("Population - " + string)print("Random values chosen from the population - ", random_vals)def pick_from_list_population():lst = ["hi", "hello", "educative", "edpresso"]k = 10random_vals = random.choices(lst, [5, 1, 3, 2], k=k)print("Using list as population")print("Population - " , lst)print("Random values chosen from the population - ", random_vals)if __name__ == "__main__":pick_from_string_population()print("---" * 8)pick_from_list_population()
Explanation
-
Lines 3–9: We define a function called
pick_from_string_populationwhere we pickkrandom characters from the string using thechoices()method. -
Lines 11–17: We define a function called
pick_from_list_populationwhere we pickkrandom element from the list using thechoices()method. -
Lines 20–23: We define the
main()method invoke thepick_from_string_populationandpick_from_list_populationmethods.