ExampleEdit & Run

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))
copy
Output:
mango [Finished in 0.01293731015175581s]

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. 

ExampleEdit & Run

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)
copy
Output:
orange [Finished in 0.01172669418156147s]

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.

ExampleEdit & Run
import random

my_list = ('Python', 'C++', 'Java', 'PHP', 'Javascript')

print(random.choice(my_list))
copy
Output:
Javascript [Finished in 0.011748033110052347s]

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

Syntax:
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.

ExampleEdit & Run

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)
copy
Output:
Paris France [Finished in 0.011185772716999054s]

The random.randint() function

The randint() function returns a random integer in a specified range.

Syntax:
randint(start, stop)
copy

With this function, there will be no conversions needed since the index will already be in integer format.

ExampleEdit & Run

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])
copy
Output:
(7, 8) [Finished in 0.011428999248892069s]

The random.choice() Function

This function offers the most direct way to pick a random element from any collection.

ExampleEdit & Run

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])
copy
Output:
cow mowwww [Finished in 0.011898591183125973s]
ExampleEdit & Run

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)
copy
Output:
Japan [Finished in 0.01126388506963849s]

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.

Syntax:
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.
ExampleEdit & Run
import random

items = range(100)

#Select 10 items from the range
print(random.choices(items, k = 10))
copy
Output:
[38, 3, 20, 58, 73, 48, 52, 41, 61, 27] [Finished in 0.011374350637197495s]
ExampleEdit & Run
import random

cities = ['Bern', 'Berlin', 'Rome', 'Budapest', 'Copenhagen', 'Paris', 'Kigali']

#pick 3 random items from the list
print(random.choices(cities, k = 3))
copy
Output:
['Berlin', 'Berlin', 'Rome'] [Finished in 0.01152823306620121s]

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.

Syntax:
sample(seq, k, counts = None)
copy
ExampleEdit & Run
import random

items = range(100)

#pick 3 random items from the list
print(random.sample(items, 10))
copy
Output:
[85, 59, 33, 57, 77, 96, 95, 54, 64, 23] [Finished in 0.011707684025168419s]