python random - ghdrako/doc_snipets GitHub Wiki

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]