Assume I have the following list:
foo = [\'a\', \'b\', \'c\', \'d\', \'e\']
What is the simplest way to retrieve an item at random from thi
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)
& 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