2.3.1. Get Elements# random.choice: Get a Randomly Selected Element From a Python List#

Besides getting a random number, you can also get a random element from a Python list using random. In the code below, “stay at home” was picked randomly from a list of options.

import random 

to_do_tonight = ['stay at home', 'attend party', 'do exercise']

'attend party' random.choices: Get Weighted Random Choices From a Python List#

If you want to get a list of random elements from a specific list, use random.choices. This method also allows you to weigh the possibility for each value with the weights parameter.

In the code below, I use random.choices to get a list of 10 random values. 0 is two times more likely to be selected than 1 and is ten times more likely to be selected than 2.

import random 

random.choices([0, 1, 2], weights=[10, 5, 1], k=10)
[0, 0, 1, 0, 0, 1, 1, 0, 0, 0] random.sample: Get Multiple Random Elements from a Python List#

If you want to get n random elements from a list, use random.sample.

import random

nums = [1, 2, 3, 4, 5]
random_nums = random.sample(nums, 2)
[2, 1] heapq: Find n Max Values of a Python List#

If you want to extract n max values from a large Python list, using heapq will speed up the code.

In the code below, using heapq is more than 2 times faster than using sorting and indexing. Both methods try to find the max values of a list of 10000 items.

import heapq
import random
from timeit import timeit

l = random.sample(range(0, 10000), 10000)

def get_n_max_sorting(l: list, n: int):
    l = sorted(l, reverse=True)
    return l[:n]

def get_n_max_heapq(l: list, n: int):
    return heapq.nlargest(n, l)
expSize = 1000
n = 100
time_sorting = timeit("get_n_max_sorting(l, n)", number=expSize,
time_heapq = timeit('get_n_max_heapq(l, n)', number=expSize,

ratio = round(time_sorting/time_heapq, 3)
print(f'Run {expSize} experiments. Using heapq is {ratio} times'
' faster than using sorting')
Run 1000 experiments. Using heapq is 2.827 times faster than using sorting