How do I retrieve an item at random from the following list?
foo = ['a', 'b', 'c', 'd', 'e']
How do I retrieve an item at random from the following list?
foo = ['a', 'b', 'c', 'd', 'e']
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 secrets.choice():
import secrets
foo = ['battery', 'correct', 'horse', 'staple']
print(secrets.choice(foo))
secrets is new in Python 3.6. On older versions of Python you can use the random.SystemRandom class:
import random
secure_random = random.SystemRandom()
print(secure_random.choice(foo))
NumPy solution: numpy.random.choice
For this question, it works the same as the accepted answer (import random; random.choice()), but I added it because the programmer may have imported NumPy already (like me)
And also there are some differences between the two methods that may concern your actual use case.
import numpy as np
np.random.choice(foo) # randomly selects a single item
For reproducibility, you can do:
np.random.seed(123)
np.random.choice(foo) # first call will always return 'c'
For samples of one or more items, returned as an array, pass the size argument:
np.random.choice(foo, 5) # sample with replacement (default)
np.random.choice(foo, 5, False) # sample without replacement
I usually use the random module for working with lists and randomization
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
random.sample methodThe sample method returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples.
import random
lst = ['a', 'b', 'c', 'd', 'e']
random.seed(0) # remove this line, if you want different results for each run
rand_lst = random.sample(lst,3) # 3 is the number of sample you want to retrieve
print(rand_lst)
Output:['d', 'e', 'a']
here is a running code https://onecompiler.com/python/3xem5jjvz
import random
my_list = [1, 2, 3, 4, 5]
num_selections = 2
new_list = random.sample(my_list, num_selections)
randIndex = random.sample(range(len(my_list)), n_selections)
randIndex.sort()
new_list = [my_list[i] for i in randIndex]
Duplicate of https://stackoverflow.com/a/49682832/4383027
You could just:
from random import randint
foo = ["a", "b", "c", "d", "e"]
print(foo[randint(0,4)])
This may already be an answer but you could use random.shuffle. Example:
import random
foo = ['a', 'b', 'c', 'd', 'e']
random.shuffle(foo)
The recommended numpy way is now to use an explicit RNG:
from numpy.random import default_rng
rng = default_rng()
rng.choice(foo)