python random - ghdrako/doc_snipets GitHub Wiki

Note! Python’s random module is not a secure source of random data. It is a pseudorandom generator seeded with the current system time. It is trivial to generate all of the possible passwords this script could have made for the past year or more. The passwords it provides should not be used for anything, except maybe throwaway testing. The correct thing you want is the Python secrets module.

import random

four_uniform_randoms = [random.random() for _ in range(4)]

if you want to get reproducible results use seed

random.seed(10) # set the seed to 10
print random.random() # 0.57140259469
random.seed(10) # reset the seed to 10
print random.random() # 0.57140259469 again
random.randrange(10) # choose randomly from range(10) = [0, 1, ..., 9]
random.randrange(3, 6) # choose randomly from range(3, 6) = [3, 4, 5]

Randomize elements order

up_to_ten = range(10)
random.shuffle(up_to_ten)
print up_to_ten
# [2, 5, 1, 9, 7, 3, 8, 6, 4, 0]

Random choose element from list

my_best_friend = random.choice(["Alice", "Bob", "Charlie"]) 

randomly choose a sample of elements without replacement (i.e.,with no duplicates), you can use random.sample:

lottery_numbers = range(60)
winning_numbers = random.sample(lottery_numbers, 6) # [16, 36, 10, 6, 25, 9]

To choose a sample of elements with replacement (i.e., allowing duplicates), you can just make multiple calls to random.choice:

four_with_replacement = [random.choice(range(10))
 for _ in range(4)]
# [9, 4, 4, 2]