Random Module in Python

Random Module in Python

For a better reading experience, check the published document


What can Random do?

"random" is a simple mathematical module, yet provides a lot of advanced methods associated with probability theories. It can simulate random choice from a set of elements, shuffle a list randomly, and even generate a set of random numeric or non-numeric elements.



Importing the module

from random import *



Simple random methods

Define a list for testing

myList = [1,5,8,9,23,9,7,8,91,2,5,9,94,8,5]

random methods:

random()        # returns a random number between 0 and 1
randint(1, 6)   # return a number randomly between 1 to 6

randrange(6)            # return random integer from 0 to 6 
randrange(0, 100, 2)    # return random integer from 0 to 100 but with taking steps of 2 (0, 2, 4, 6, …)

choice(myList)  # return an element randomly from the list 
choices(myList, k=10)       # choose 10 element randomly from the list with equal probability

sample(myList, k=10)        # choose 10 unique element randomly from the list
sample(["red", "blue"], counts=[4, 2], k=3)     
# duplicate the samples with the corresponding samples, 
# and choose 3 unique element randomly from this list: [“red”, “red”, “red”, “red”, “blue” , “blue”]

shuffle(myList) # shuffle (change positions) of the elements in the list



Complicated random methods

gauss(5, 20)        # generates a Gaussian distribution float number, 
# (5) is the mean (mu), (20) is the standard deviation (sigma)

# --- System Random ---

rnd = SystemRandom()       # create a system random object

rnd.getrandbits(2)         
# generate a random integer which its binary value consists of (2) digits: [0, 1, 2 ,3] 
# because their corresponding binary values are: 
# [00, 01, 10, 11] all of which consists of 2 binary digits

rnd.randbytes(3)           
# generates 3 random bytes, such:
# b'0i)'
# b'\x0f\xb7\xda'

Comments