Get a random element from a list
#import the random module
import random
my_list = ['apple', 'banana', 'orange', 'strawberry', 'mango']
#pick a random item from the list
print(random.choice(my_list))
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.
Using the random.random()
function to select a random element from a list
import random
my_list = ['apple', 'banana', 'orange', 'strawberry', 'mango']
#use the random.random function to get a random index
random_index = int(random.random() * len(my_list)-1)
item = my_list[random_index]
print(item)
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.
import random
my_list = ('Python', 'C++', 'Java', 'PHP', 'Javascript')
print(random.choice(my_list))
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)
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.
Use the randrange()
function to get a random element from a dictionary
import random
d = { 'London': 'United Kingdom', 'Paris': 'France', 'Berlin': 'Germany', 'Rome': 'Italy', 'Madrid': 'Spain', 'Moscow': 'Russia', 'Athens': 'Greece' }
random_index = int(random.randrange(0, len(d)-1))
random_key = list(d.keys())[random_index]
random_value = d[random_key]
print(random_key, random_value)
The random.randint() function
The randint()
function returns a random integer in a specified range.
randint(start, stop)
With this function, there will be no conversions needed since the index will already be in integer format.
Using the randint()
function to select a random element from a tuple
import random
T = ((1, 2), (3, 4), (5, 6), (7, 8), (8, 10))
#get a random index
index = random.randint(0, len(T)-1)
print(T[index])
The random.choice() Function
This function offers the most direct way to pick a random element from any collection.
Pick a random element from a dictionary
import random
d = {'cat': 'Purrr', 'dog': 'Woof', 'cow':'mowwww'}
random_key = random.choice(list(d.keys()))
print(random_key, d[random_key])
Choose a random element from a set
import random
my_set = {'Japan', 'Kenya', 'Canada', 'China', 'France'}
#First convert the set into a list
random_element = random.choice(list(my_set))
print(random_element)
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)
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. |
import random
items = range(100)
#Select 10 items from the range
print(random.choices(items, k = 10))
import random
cities = ['Bern', 'Berlin', 'Rome', 'Budapest', 'Copenhagen', 'Paris', 'Kigali']
#pick 3 random items from the list
print(random.choices(cities, k = 3))
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)
import random
items = range(100)
#pick 3 random items from the list
print(random.sample(items, 10))