
Get a random element from a list in Python
To select a random element of a Python list, use the random.choice()
.
import random
s1 = [1, 2, 3, 4, 5, 6]
s2 = ['a', 'b', 'c']
a1 = random.choice(s1)
a2 = random.choice(s2)
print(a1) # 2
print(a2) # b
You can use the secrets
module from Python 3.6.
import secrets
s1 = [1, 2, 3, 4, 5, 6]
s2 = ['a', 'b', 'c']
a1 = secrets.choice(s1)
a2 = secrets.choice(s2)
print(a1) # 6
print(a2) # c
Reference: Python secrets
Comments
Powered by Markdown