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
How to randomly select an item from a list?
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?
If you want close to truly random, then I suggest secrets.choice
from the standard library (New in Python 3.6.):
>>> from secrets import choice # Python 3 only
>>> choice(list('abcde'))
'c'
The above is equivalent to my former recommendation, using a SystemRandom
object from the random
module with the choice
method - available earlier in Python 2:
>>> import random # Python 2 compatible
>>> sr = random.SystemRandom()
>>> foo = list('abcde')
>>> foo
['a', 'b', 'c', 'd', 'e']
And now:
>>> sr.choice(foo)
'd'
>>> sr.choice(foo)
'e'
>>> sr.choice(foo)
'a'
>>> sr.choice(foo)
'b'
>>> sr.choice(foo)
'a'
>>> sr.choice(foo)
'c'
>>> sr.choice(foo)
'c'
If you want a deterministic pseudorandom selection, use the choice
function (which is actually a bound method on a Random
object):
>>> random.choice
>
It seems random, but it's actually not, which we can see if we reseed it repeatedly:
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
This is not about whether random.choice is truly random or not. If you fix the seed, you will get the reproducible results -- and that's what seed is designed for. You can pass a seed to SystemRandom, too.
sr = random.SystemRandom(42)
Well, yes you can pass it a "seed" argument, but you'll see that the SystemRandom object simply ignores it:
def seed(self, *args, **kwds):
"Stub method. Not used for a system random number generator."
return None