Python Random module

The Python Random module is a built-in module for generating random integers in Python. These are sort of fake random numbers which do not possess true randomness. We can therefore use this module to generate random numbers, display a random item for a list or string, and so on.

Generate Random Floats

The random.random() function gives a float number that ranges from 0.0 to 1.0. There are no parameters required for this function.

random.random():- Returns The second random floating point value within [0.0 and 1) is returned.

random.uniform(a, b):- Generates a random floating point R in which a <= R <= b if a <= b and b <= R <= a if b < a.

random.expovariate(lambda):- Returns the random value according to exponential distribution.

random.gauss(mu, sigma):- Returns the random value according to gaussian distribution.

There are other distributions also, such as Gamma Distribution, Normal Distribution, etc.

Code

import random
num=random.random()
print(num)

Output:

0.3232640977876686

Generate Random Integers

The random.randint() function generates a random integer from the range of numbers supplied.

Code

import random
num = random.randint(1500)
print( num )

Output:

Generate Random Numbers within a Defined Range

The random.randrange() function selects an item randomly from the given range defined by the start, the stop, and the step parameters. By default, the start is set to 0. Likewise, the step is set to 1 by default.

Code

import random
num = random.randrange(110)
print( num )
num = random.randrange(1102)
print( num )
num = random.randrange(010110)
print( num )

Output:

4
9
20

Select Random Elements

The random.choice() function selects an item from a non-empty series at random. An IndexError is thrown when the parameter is an empty series.

Code

import random
random_s = random.choice('Random Module'#a string
print( random_s )
random_l = random.choice([2354765234545]) #a list
print( random_l )
random_s = random.choice((1264235434)) #a set
print( random_s )

Output:

M
765
54

Shuffle Elements Randomly

A general sequence, like integers or floating-point series, can be a group of things like a List / Set. The random module contains methods that we can use to add randomization to the series.

The random.shuffle() function shuffles the entries in a list at random.

Code

a_list = [342365862343]
random.shuffle( a_list )
print( a_list )
random.shuffle( a_list )
print( a_list )

Output:

[23, 43, 86, 65, 34, 23]
[65, 23, 86, 23, 34, 43]

Random Seed

We normally use the time of the system to ensure that the software delivers a different output each time we execute it because pseudorandom synthesis is dependent on the preceding number. As a result, we employ seeds.

We can specify a seed to have an initial number using Python’s random.seed() function. This seed number determines a random number generator’s outcome; therefore, if it stays the same, the outcome will continue to be the same.

Code

import random
random.seed(2)
print('Generating 5 random numbers: ')
print([ random.randint(1300for r in range(6)])
# Reseting the seed value to 1
random.seed(2)
# We will get the same numbers as before
print([random.randint(1300for i in range(6)])

Output:

Generating 5 random numbers: 
[29, 47, 44, 185, 87, 158]
[29, 47, 44, 185, 87, 158]

Various Functions of Random Module

Following is the list of functions available in the random module.

Function Description
seed(a=None, version=2) This function creates a new random number.
getstate() This method provides an object reflecting the generator’s present state. Provide the argument to setstate() to recover the state.
setstate(state) Providing the state object resets the function’s state at the time getstate() was invoked.
getrandbits(k) This function provides a Python integer having k random bits. This is important for random number production algorithms like randrange(), which can manage arbitrarily huge ranges.
randrange(start, stop[, step]) From the range, it produces a random integer.
randint(a, b) Provides an integer within a and b at random (both inclusive). If a > b, a ValueError is thrown.
choice(seq) Produce a non-empty series item at random.
shuffle(seq) Change the order.
sample(population, k) Display a list of k-size unique entries from the population series.
random() This function creates a new random number.
uniform(a, b) This method provides an object reflecting the generator’s present state. Provide the argument to setstate() to recover the state.
triangular(low, high, mode) Providing the state object resets the function’s state at the time getstate() was invoked.
betavariate(alpha, beta) Beta distribution
expovariate(lambd) Exponential distribution
gammavariate(alpha, beta) Gamma distribution
gauss(mu, sigma) Gaussian distribution
lognormvariate(mu, sigma) Log normal distribution
normalvariate(mu, sigma) Normal distribution
vonmisesvariate(mu, kappa) Vonmises distribution
paretovariate(alpha) Pareto distribution
weibullvariate(alpha, beta) Weibull distribution

We learned about various methods that Python’s random module provides us with for dealing with Integers, floating-point numbers, and other sequences like Lists, tuples, etc. We also looked at how the seed affects the pseudo – random number pattern.

Leave a Reply

Your email address will not be published. Required fields are marked *