I'dl like to generate some alphanumeric passwords in python. Some possible ways are:
import string
from random import sample, choice
chars = string.letters + string.digits
length = 8
''.join(sample(chars,length)) # way 1
''.join([choice(chars) for i in range(length)]) # way 2
But I don't like both because:
i
variable unused and I can't find good way how to avoid thatSo, any other good options?
P.S. So here we are with some testing with timeit
for 100000 iterations:
''.join(sample(chars,length)) # way 1; 2.5 seconds
''.join([choice(chars) for i in range(length)]) # way 2; 1.8 seconds (optimizer helps?)
''.join(choice(chars) for _ in range(length)) # way 3; 1.8 seconds
''.join(choice(chars) for _ in xrange(length)) # way 4; 1.73 seconds
''.join(map(lambda x: random.choice(chars), range(length))) # way 5; 2.27 seconds
So, the winner is ''.join(choice(chars) for _ in xrange(length))
.