Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to generate some alphanumeric passwords in python. Some feasible 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

Any other good options?

The below 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)).

1 Answer

0 votes
by (108k points)

You simply need to use the secrets package to generate cryptographically safe passwords, which is available starting in Python 3.6.:

import secrets

import string

alphabet = string.ascii_letters + string.digits

password = ''.join(secrets.choice(alphabet) for i in range(20))  # for a 20-character password

You can also add a string. punctuation or even just using string. printable for a wider set of characters.

Kick-start your career in Python with the perfect Python online Course now!

Browse Categories

...