Working with Random Numbers in Python An overview for working with randomness in Python, using only functionality built into the standard library and CPython itself.

Generating Random Floats Between 0.0 and 1.0 The random.random() function returns a random float in the interval [0.0, 1.0). This means the returned random number will always be smaller than the right-hand endpoint (1.0). This is also known as a semi-open range: >>> import random >>> random . random () 0.11981376476232541 >>> random . random () 0.757859420322092 >>> random . random () 0.7384012347073081

Generating Random Ints Between x and y This is how you can generate a random integer between two endpoints in Python with the random.randint() function. This spans the full [x, y] interval and may include both endpoints: >>> import random >>> random . randint ( 1 , 10 ) 10 >>> random . randint ( 1 , 10 ) 3 >>> random . randint ( 1 , 10 ) 7 With the random.randrange() function you can exclude the right-hand side of the interval, meaning the generated number always lies within [x, y) and it will always be smaller than the right endpoint: >>> import random >>> random . randrange ( 1 , 10 ) 5 >>> random . randrange ( 1 , 10 ) 3 >>> random . randrange ( 1 , 10 ) 4

Generating Random Floats Between x and y If you need to generate random float numbers that lie within a specifc [x, y] interval you can use the random.uniform function: >>> import random >>> random . uniform ( 1 , 10 ) 7.850184644194309 >>> random . uniform ( 1 , 10 ) 4.00388600011348 >>> random . uniform ( 1 , 10 ) 6.888959882650279

Picking a Random Element From a List To pick a random element from a non-empty sequence (like a list or a tuple) you can use Python’s random.choice function: >>> import random >>> items = [ 'one' , 'two' , 'three' , 'four' , 'five' ] >>> random . choice ( items ) 'five' >>> random . choice ( items ) 'one' >>> random . choice ( items ) 'four' This works for any non-empty sequence, however it will throw an IndexError exception if the sequence is empty.

Randomizing a List of Elements You can randomize a sequence in place using the random.shuffle function. This will modify the sequence object and randomize the order of elements: >>> import random >>> items = [ 'one' , 'two' , 'three' , 'four' , 'five' ] >>> random . shuffle ( items ) >>> items [ 'four' , 'one' , 'five' , 'three' , 'two' ] If you’d rather not mutate the original you’ll need to make a copy first and then shuffle the copy. You can create copies of Python objects with the copy module.

Picking n Random Samples From a List of Elements To pick a random sample of n unique elements from a sequence, use the random.sample function. It performs random sampling without replacement: >>> import random >>> items = [ 'one' , 'two' , 'three' , 'four' , 'five' ] >>> random . sample ( items , 3 ) [ 'one' , 'five' , 'two' ] >>> random . sample ( items , 3 ) [ 'five' , 'four' , 'two' ] >>> random . sample ( items , 3 ) [ 'three' , 'two' , 'five' ]