How to Randomly Select a Element from List in Python
Created
Modified
Using random.choice Method
The random.choice()
method returns a random element from the non-empty sequence seq. If seq is empty, raises IndexError. For example,
#!/usr/bin/python3
# Import module
import random
a = ['a', 'b', 'c', 'd']
print(random.choice(a))
c
Using secrets.choice Method
For cryptographically secure random choices (e.g., for generating a passphrase from a wordlist), use secrets.choice():
#!/usr/bin/python3
# Import module
import secrets
a = ['a', 'b', 'c', 'd']
print(secrets.choice(a))
b
Using random.sample Method
The sample method returns a new list containing elements from the population while leaving the original population unchanged.
#!/usr/bin/python3
# Import module
import random
a = ['a', 'b', 'c', 'd']
l = random.sample(a, 2)
print(l)
['b', 'a']
By default the random number generator uses the current system time.