[Tutor] Generating random alphanumeric codes

Martin A. Brown martin at linux-ip.net
Tue Jun 26 21:47:06 CEST 2012


 : Would anyone have tips on how to generate random 4-digit 
 : alphanumeric codes in python? Also, how does one calculate the 
 : number of possible combinations?

Here are some thoughts that come to my mind:

  import string
  import random

  # -- technique #1, using random.choice
  print ''.join([random.choice(string.lowercase) for x in range(4)])

  # -- technique #2, using random.shuffle
  t = [ x for x in string.lowercase ]

  # -- technique #3, using random.sample

I would be quite surprised if there were not more efficient ways of 
accomplishing this.


Martin A. Brown

More information about the Tutor mailing list