generate random digits with length of 5

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sun Sep 28 16:19:22 EDT 2008


sotirac:
>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5 elements

But note that's without replacement. So if you want really random
numbers you can do this:

>>> from string import digits
>>> from random import choice
>>> "".join(choice(digits) for d in xrange(5))
'93898'

If you need more speed you can invent other solutions, like (but I
don't know if it's faster):

>>> from random import shuffle
>>> ldigits = list(digits)
>>> ldigits
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> shuffle(ldigits)
>>> ldigits
['3', '8', '6', '4', '9', '7', '5', '2', '0', '1']
>>> "".join(ldigits[:5])
'38649'

But this may be the most efficient way:

>>> from random import randrange
>>> str(randrange(100000)).zfill(5)
'37802'

Bye,
bearophile



More information about the Python-list mailing list