This post is also available as a PDF and a Jupyter Notebook.

Here we look at the standard Python random number generator. It uses a *Mersenne Twister*, one of the mostly commonly-used random number generators. The generator can generate random integers, random sequences, and random numbers according to a number of different distributions.

## Importing the random module and setting a random seed

`import random`

Random numbers can be repeatable in the sequence they are generated if a ’seed’ is given. If no seed is given the random number sequence generated each time will be different.

```
random.seed() # This will reset the random seed so that the random number sequence will be different each time
random.seed(10) # giving a number will lead to a repeatable random number sequence each time
```

## Random numbers

Random integers between (and including) a minimum and maximum:

```
i
print (random.randint(0,5))
OUT:
4
```

Return a random number between 0 and 1:

```
print (random.random())
OUT:
0.032585065282054626
```

Return a number (floating, not integer) between a & b:

```
print (random.uniform(0,5))
OUT:
2.412808372754279
```

Select from normal distribution (with mu, sigma):

```
print (random.normalvariate(10,3))
OUT:
5.3538059684648855
```

Other distributions (see help(random) for more info after importing random module):

Lognormal, Exponential, Beta, Gaussian, Gamma, Weibul

## Generating random sequences

The random library may also be used to shuffle a list:

```
deck = ['ace','two','three','four']
random.shuffle(deck)
print (deck)
OUT:
['three', 'ace', 'two', 'four']
```

Sampling without replacement:

```
sample = random.sample([10, 20, 30, 40, 50], k=4) # k is the number of samples to select
print (sample)
OUT:
[20, 30, 10, 50]
```

Sampling with replacement:

```
pick_from = ['red', 'black', 'green']
sample = random.choices(pick_from, k=10)
print(sample)
OUT:
['black', 'red', 'black', 'green', 'red', 'red', 'black', 'red', 'black', 'green']
```

Sampling with replacement and weighted sampling:

```
pick_from = ['red', 'black', 'green']
pick_weights = [18, 18, 2]
sample = random.choices(pick_from, pick_weights, k=10)
print(sample)
OUT:
['black', 'red', 'red', 'red', 'black', 'red', 'red', 'black', 'red', 'black']
```

## One thought on “9. Python basics: Random numbers and sequences”