HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How can I randomly select (choose) an item from a list (get a random element)?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
getrandomlyhowfromrandomchooseelementlistcanitem

Problem

How do I retrieve an item at random from the following list?
foo = ['a', 'b', 'c', 'd', 'e']

Solution

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))

Code Snippets

import random

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

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

secure_random = random.SystemRandom()
print(secure_random.choice(foo))

Context

Stack Overflow Q#306400, score: 3540

Revisions (0)

No revisions yet.