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?
In Python, you can randomly sample elements from a list with choice() , sample() , and choices() of the random module. These functions can also be applied to a string and tuple. choice() returns one random element, and sample() and choices() return a list of multiple random elements.
You can use random. randint() and random. randrange() to generate the random numbers, but it can repeat the numbers.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With