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.
choices(population, weights=None, *, cum_weights=None, k=1)
population
: This is a mandatory parameter that can be a list
, tuple
, or string
. 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
weights
andcum_weights
must be the same length as the population sequence. Specifyingweights
andcum_weights
throws an error.
This method returns random values chosen from the population.
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()
Lines 3–9: We define a function called pick_from_string_population
where we pick k
random characters from the string using the choices()
method.
Lines 11–17: We define a function called pick_from_list_population
where we pick k
random element from the list using the choices()
method.
Lines 20–23: We define the main()
method invoke the pick_from_string_population
and pick_from_list_population
methods.