# Python Random Module – Generate Random Numbers/Sequences

Here’s an introduction to Python’s random module, which is used to generate pseudo-random numbers for a variety of probabilistic distributions.

## Random Module Methods In Python

Let’s look at the various Python random module methods for generating random numbers in your Python program.

### 1. seed()

This initiates the operation of a random number generator. In order to generate a new random sequence, a seed that is dependent on the current system time must be set first. random.seed() is responsible for setting the seed used in random number generation.

### 2. getState()

When this function is called, it returns an object containing the current state of the generator. To restore the state of an object, pass it through the setstate function ().

### 3. setstate(stateObj)

By passing the state object to this function, the state of the generator is restored to the point at which getstate() was called.

```#importing Random Library
import random

random.seed(1)

#Get The Current State
stateObj = random.getstate()

#Generating 5 Sequence Of Numbers
for i in range(0, 5):
print(random.randint(0,100))

#Using set state to generate same
#Random Numbers sequece.
random.setstate(stateObj)

print("Generating Another Seuqence with same state.")

for i in range(0,5):
print(random.randint(0,100))```

Output:

``````17
72
97
8
32
Generating Another Seuqence with same state.
17
72
97
8
32``````

### 4. getrandbits(n)

This function returns a Python integer that contains k random bits. This is useful for random number generation methods such as randrange(), which can handle arbitrarily large ranges of numbers.

Let’s look at some Python code that uses the above functions to generate random numbers.

```#importing Random Library
import random

#Generate Random Number with 16 bits
getRandomNum = random.getrandbits(16)

#Printing The 16 Bit Random Number
print("The 16Bit Random Number is: ",getRandomNum)```

Output:

``The 16Bit Random Number is:  22523``

## Generate Random Integers

Integers can be generated in a variety of ways using the random module.

### 1. Using randrange Function

Randomly selects an integer from a set of possible values (start, stop, step). Start > stop causes a ValueError to be raised.

``randrange(start, stop, step)``
```#importing Random Library
import random

#get Random Integer Between 1-100.
getRandomNum = random.randrange(1,100)

print("The Random Number is:" , getRandomNum)```

Output:

``The Random Number is: 64``

### 2. Using randint Function

A random integer between a and b is returned (both inclusive). If an is greater than b, a ValueError is thrown.

``randint(startingRangeNum, EndingRangeNum)``
```#importing Random Library
import random

#get Random Integer Between 1-500.
getRandomNum = random.randint(1,500)

print("The Random Number is:" , getRandomNum)```

Output:

``The Random Number is: 372``

## Generating Random Floating Point Number

Random floating point sequences can be generated using functions that are similar to those used to generate integers.

• a random floating-point number between [0.0 and 1.0] is returned by calling random.random().
• random.uniform(a,b) If a <= N <= b and b <= N <= a, a random floating point N is returned.
• Returns an exponentially distributed number via random.expovariate(lambda).
• This function returns a Gaussian distribution based on the values of the parameters (mu, sigma).

A similar function exists for the Normal, Gamma, and many other distributions. An illustration of how to generate these floating-point numbers is provided below:

```#Importing Random Library
import random

getRandomFloat = random.random()

print('The Random number from 0 to 1 :', getRandomFloat)

getRandomFloat = random.uniform(1, 10)
print('The Random Uniform Distribution between [1,10] :', getRandomFloat)

getRandomFloat = random.gauss(0,1)
print('Gaussian Distribution Random Value is: ', getRandomFloat)

getRandomFloat = random.expovariate(0.1)
print('The Exponential Distribution Random Value Is:', getRandomFloat)

getRandomFloat = random.normalvariate(1, 5)
print('Normal Distribution with mean = 1 and standard deviation = 2:', getRandomFloat )```

Output:

``````The Random number from 0 to 1 : 0.20202868092294834
The Random Uniform Distribution between [1,10] : 3.420663302866991
Gaussian Distribution Random Value is:  -0.045934588283933105
The Exponential Distribution Random Value Is: 11.91366597371402
Normal Distribution with mean = 1 and standard deviation = 2: -7.0377273746819``````

## Generate Random Sequences Using Random Module

A generic sequence is similar to integers and floating-point sequences in that it can be a collection of items, such as a List or a Tuple. The random module contains a number of useful functions that can be used to introduce a randomness state into sequences.

### 1. random.shuffle(n)

This is used to shuffle the sequence in place while it is being played. A sequence can be any list or tuple of elements that contains one or more of the elements.

```#Importing Random Function
import random

#Get The Random Sequence Generated
genRandomSequence = [random.randint(0, i) for i in range(15)]

print('No Shuffle Applied: ', genRandomSequence)

random.shuffle(genRandomSequence)

print('After Applying Shuffle: ', genRandomSequence)```

Output:

``````No Shuffle Applied:  [0, 0, 0, 3, 1, 3, 2, 2, 1, 0, 6, 6, 2, 4, 10]
After Applying Shuffle:  [1, 0, 2, 2, 1, 0, 4, 6, 2, 0, 3, 3, 6, 0, 10]``````

### 2. random.sample(sampleData, k)

A random sample from a sequence of length k is returned by this function.

```#Importing Random Function
import random

listVal = [1,2,3,4,5,6]

print(listVal)

for i in range(3):
getRandomData = random.sample(listVal, 2)
print('random sample:', getRandomData)```

Output:

``````[1, 2, 3, 4, 5, 6]
random sample: [6, 4]
random sample: [4, 5]
random sample: [4, 5]``````

### 3. random.choice(seqObj)

In practice, this is a commonly used function when you want to select an item at random from a list or sequence of items, for example.

```#Importing Random Function
import random

listVal = [1,2,3,4,5,6]

print(listVal)

for i in range(3):
getRandomData = random.choice(listVal)
print('The Random Sample Is:', getRandomData)```

Output:

``````[1, 2, 3, 4, 5, 6]
The Random Sample Is: 4
The Random Sample Is: 6
The Random Sample Is: 1``````

## Wrap Up

It was demonstrated to us how to use the various methods provided by Python’s random module to deal with Integers, floating-point numbers, and other sequences such as Lists, among other things. We also looked at how the seed affects the sequence of pseudorandom numbers that are generated.

If you have any questions about the above functions or code examples, please leave them in the comments section and I will get back to you as soon as possible.