The real world is mischievously random .

Quick overview of random module in Python

Kishor Keshav

--

Python has provided inbuilt modules for various tasks frequently encountered by programmers. They are already available as a part of standard library. So, there’s no need to install it. Some of the frequently used modules are os module, random module, math module, statistics module, collection module, sys module, time module, and calendar module.

I am going to present random module, that is a necessarily required in the domain of game playing, machine learning, cryptography, and scientific simulations, etc. Apart from standard library random module, here you will also find some examples of functions from the random module from numpy library, which is very essential for manipulating array required in the domain of machine learning (specifically for linear algebra) and for the scientific computations in general.

Random Module:

It is a built-in module to generate the pseudo-random numbers(not truly random but generated by computer algorithms). To use it, add “import random” at the beginning of your code. The module can be used to perform certain actions, such as getting a random number, selecting a random elements from a list, shuffling elements randomly, etc. The following code snippets illustrates the use of important functions in random module.

A) Generating random integers :

Function randint(a,b) generates a random integer in the closed interval [a,b]

import random
print(random.randint(-5,5))

You may get output such as Randomly selected number is 3. Note the the initial and final numbers (a,b) could also be generated in the process.

Function randrange(beg, end, step) can generate a random number from a specified integer range with a specified step as a third argument. So possible numbers that could be generated in the following code are -10,-8, … -2,0,2,4, … 10. All the arguments of this functions are integer and the default values of beg and step are 0 and 1 respectively.

print("randomly generated number is ", random.randrange(-10,10,2))

Here you may get output such as randomly generated number is 2

B) Generating Random float numbers

We can also generate floating point numbers in Python using random.random() and random.uniform() functions.

random.random() gives you a random floating point number in the semi-open interval [0.0, 1.0)

random.uniform(a, b) gives you a random floating point number in the range [a, b]

C) Generating random matrices

Many times we need random matrices to be created. The random module from numpy package is very useful for the same. The following two examples make it clear. Do not forget to include the following line before trying to generate the numbers.

import numpy as np

To create a random integer matrix in the semi-open interval [0,10) of size 3x4 use the following code. This will generate 3x4 matrix of numbers from 0 to 9 but not 10.

array = np.random.randint(10, size=(3, 4))

To create a random float matrix of size 3x2 in the interval [0,1] use the following code

np.random.uniform(0.0, 1.0, size = (3,2))

D) Other useful functions

Function seed() is used to save the state of a random function, so that with specific seed value passed as an argument, one can generate same random numbers on multiple executions of the code, on the same or on different machines.

The program below generates the same value when the same seed is passed as an argument, and the different value for the different seed argument. Give it a try.

random.seed(1)
print(random.randrange(-10,10,2),end='')
random.seed(2)
print(random.randrange(-10,10,2),end='')
random.seed(1)
print(random.randrange(-10,10,2))

The output of the above code in my case was -6 -10 -6. Note that same seed of 1 here gives you the same random output.

Function choice(): This function returns a random item from a list, tuple, or a string. Let us try a piece of code to print a random value from the list

#Problem: randomly generate outcome of rolling a dice 
dice_roll = [1, 2, 3, 4, 5, 6]
print(random.choice(dice_roll))

The above program will print any random value out of six face values of a dice. The same can also be achieved using the following code.

print(random.randint(1,6))

You can implement a biased dice that will allow you to assign probability to each face using numpy package. Note that the probabilities assigned are passed as one of the arguments ( in a list), to the choice function. First import the numpy package as np and then use np.random.choice() as follows.

import numpy as np
np.random.choice(np.arange(1,7), p=[0.15, 0.2, 0.3,0.2, 0.15,0.0])

Note that above code will not generate the face value of 6, as its probability assigned is 0.0

Let us try to simulate tossing of a coin.

# Simulate a coin toss
result=['Head','Tail']
print("\nYou tossed",random.choice(result))

Now let us write a piece of code for selecting a random card from a deck of cards. Give it a try it will print some random card.

suits=['♣','♦','♥','♠'] #clubs (♣), diamonds (♦), hearts (♥) and spades (♠)
cardno= [1,2,3,4,5,6,7,8,9,10,'J','Q','K']
s=random.choice(suits)
cv=random.choice(cardno)
card=s+str(cv)
print("\nCard selected is ",card)

A card is specified by suite and a card value. Hence the final card is formed by concatenating the two strings s(for suit) and cv for card value.

The output I got is Card selected is ♦7

Function shuffle(): It is used to shuffle a sequence.

s=[‘s’,’u’,’r’,’f’,’a’,'c','e']
random.shuffle(s)
print(s)

The output may be something like [‘f’, ‘s’, ‘e’, ‘c’, ‘r’, ‘u’, ‘a’], which is a shuffled version of the original string.

Note that shuffle() modifies the original sequence object. Hence it can be used only with the objects that are mutable (like lists), but can not be used with immutable objects like tuples.

Now let us take one more example of shuffling. Suppose we want to form a deck of cards and then shuffle it. We may represent a card using a string as in “♦7” for seven of diamond. Following codes forms an ordered deck of cards.

# forming a deck of cardsdeck=[]
for s in suits:
for card in cardno:
deck.append(s+str(card))
print(deck)

The output is :

[‘♣1’, ‘♣2’, ‘♣3’, ‘♣4’, ‘♣5’, ‘♣6’, ‘♣7’, ‘♣8’, ‘♣9’, ‘♣10’, ‘♣J’, ‘♣Q’, ‘♣K’, ‘♦1’, ‘♦2’, ‘♦3’, ‘♦4’, ‘♦5’, ‘♦6’, ‘♦7’, ‘♦8’, ‘♦9’, ‘♦10’, ‘♦J’, ‘♦Q’, ‘♦K’, ‘♥1’, ‘♥2’, ‘♥3’, ‘♥4’, ‘♥5’, ‘♥6’, ‘♥7’, ‘♥8’, ‘♥9’, ‘♥10’, ‘♥J’, ‘♥Q’, ‘♥K’, ‘♠1’, ‘♠2’, ‘♠3’, ‘♠4’, ‘♠5’, ‘♠6’, ‘♠7’, ‘♠8’, ‘♠9’, ‘♠10’, ‘♠J’, ‘♠Q’, ‘♠K’]

Now let us shuffle this deck of cards.

# Shuffling deck of cards
random.shuffle(deck)
print(deck)

The output shows the shuffled deck of cards.

[‘♥3’, ‘♥5’, ‘♣J’, ‘♠Q’, ‘♣5’, ‘♥J’, ‘♦4’, ‘♣10’, ‘♣1’, ‘♠9’, ‘♦10’, ‘♠6’, ‘♣9’, ‘♥9’, ‘♦Q’, ‘♣4’, ‘♦2’, ‘♣3’, ‘♦8’, ‘♦5’, ‘♠5’, ‘♣6’, ‘♠1’, ‘♦1’, ‘♠8’, ‘♦J’, ‘♠4’, ‘♦3’, ‘♠K’, ‘♥Q’, ‘♥8’, ‘♦K’, ‘♥6’, ‘♠7’, ‘♦7’, ‘♣K’, ‘♥K’, ‘♥2’, ‘♥7’, ‘♦9’, ‘♣8’, ‘♠J’, ‘♠2’, ‘♣Q’, ‘♣7’, ‘♠3’, ‘♥10’, ‘♥1’, ‘♣2’, ‘♦6’, ‘♥4’, ‘♠10’]

That’s all for now. Hope this introduction on random numbers is useful. Have a great weekend ahead !

--

--