A random element in a python list can easily extracted with a newly added module called "secrets".

Without secrets module, you may consider a code as show below.

import random

alist= [1,3,4,5,3,2,1]

n = random.randint(0, len(alist)-1))


There is no problem in acheiving the goal, but it does not seem pythonic.

In python 3.6, a module called "secrets" was added. It describes as below.

"The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets."

Using the secrets module you can shorten the codes 2/3 as below. 

import secrets

alist= [1,3,4,5,3,2,1]


It looks much better, cleaner so pythonic.

+ Recent posts