Choosing random item or items from a collection is a useful way to make your program more dynamic. The random module in the standard library offers various functions for randomizing selections, they includes random.choice(), random.choices()
, random.sample()
, etc .Literally speaking, most functions provided by the module can be utilized for this purpose albeit in different ways. For example the following program uses the random.random()
function to pick a random item from a list.
In the above example, we use the random.random()
function to generate a random index within the valid range of indices. The program then uses the random index generated to choose one item from the list.
While the above example works, the random module offers more specialized tools for random selections . The most obvious tool for selecting random single item from a collection is the choice()
function which does the picking directly.
In the next parts we will look at the various functions that helps us achieve random selection whether directly or indirectly.
Selecting single random item from a collection
As we have already seen above, we can select a random item from a collection by simply getting a random valid index and then getting the item in that index. There are several other function that can help us achieve.
The randrange()
function
randrange(start, stop)
copy
This function chooses a random floating point value in the range specified by start
and stop
. We can turn the value returned to an integer then use it to subscript the iterable object.
The random.randint() function
The randint()
function returns a random integer in a specified range.
randint(start, stop)
copy
With this function, there will be no conversions needed since the index will already be in integer format.
The random.choice() Function
This function offers the most direct way to pick a random element from any collection.
Selecting multiple random items from a collection
We can use the various functions offered by the random module to pick multiple random items from a list. We will not talk about choosing single items and then appending each to an iterable such as a list since the module have better functions meant for just this purpose.
The random.choices() Function
The random.choices()
function makes it possible to select multiple items from a collection, with the possibility of repeating items.
choices(seq, weight = None, cum_weight = None k = 1)
copy
seq |
Required. A sequence from which elements are to be selected. |
weight |
Optional. Weight associated with each entry in the population |
cum_weight |
Optional. cumulative weights associated with each entry in the population. |
k |
The number of random items to be returned. |
The random.sample() function
The random.sample()
function returns a list of randomly selected elements from a given items. Unlike the choices() function, the random.sample() function does not allow include duplicate elements.
sample(seq, k, counts = None)
copy