How to randomly select an item from a list?


Question

Assume I have the following list:

foo = ['a', 'b', 'c', 'd', 'e']

What is the simplest way to retrieve an item at random from this list?

1
1605
5/4/2017 8:40:51 PM

Accepted Answer

Use random.choice()

import random

foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))

For cryptographically secure random choices (e.g. for generating a passphrase from a wordlist), use random.SystemRandom class

import random

foo = ['battery', 'correct', 'horse', 'staple']
secure_random = random.SystemRandom()
print(secure_random.choice(foo))

or secrets.choice()

import secrets
foo = ['a', 'b', 'c', 'd', 'e']
print(secrets.choice(foo))
2517
4/9/2019 10:16:25 PM

If you want to randomly select more than one item from a list, or select an item from a set, I'd recommend using random.sample instead.

import random
group_of_items = {1, 2, 3, 4}               # a sequence or set will work here.
num_to_select = 2                           # set the number to select here.
list_of_random_items = random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1] 

If you're only pulling a single item from a list though, choice is less clunky, as using sample would have the syntax random.sample(some_list, 1)[0] instead of random.choice(some_list).

Unfortunately though, choice only works for a single output from sequences (such as lists or tuples). Though random.choice(tuple(some_set)) may be an option for getting a single item from a set.

EDIT: Using Secrets

As many have pointed out, if you require more secure pseudorandom samples, you should use the secrets module:

import secrets                              # imports secure module.
secure_random = secrets.SystemRandom()      # creates a secure random object.
group_of_items = {1, 2, 3, 4}               # a sequence or set will work here.
num_to_select = 2                           # set the number to select here.
list_of_random_items = secure_random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1]

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon