I. Python random modules

We will learn the following three random modules:

random.random()

random.randint()

random.choice()

Also, we will learn the following three numpy random modules:

np.random.randn()

np.random.randint()

np.random.choice()

References

Python Random Module

Python random randrange() and randint() to generate random integer number within a range

Generating Random Data in Python (Guide)

II. random()

This function is used to generate a random number between 0 and 1.

import random
# generate a random number
random.random()
## 0.651104651744994

You can generate a sequence of random numbers with a list comprehension.

The underscore (_) is used as throwaway variable.

import random
# generate a sequence of 5 random bumbers between 0 and 1
[random.random() for _ in range(5)]
## [0.7527318249198466, 0.8135985879307613, 0.5757216021018331, 0.7018595520782182, 0.2893155962115538]

III. randint()

You can generate a random integer with randint()

random.randint(1, 100)
## 8

You can generate a sequence of random integers with a list comprehension.

[random.randint(1, 100) for _ in range(10)]
## [24, 71, 71, 80, 62, 69, 37, 5, 77, 13]

IV. randrange()

The randrange() returns a randomly selected element from the specified range.

random.randrange(1, 101, 10)
## 31

You can use a list comprehension.

[random.randrange(0, 101, 10) for _ in range(10)]
## [30, 50, 80, 90, 10, 30, 80, 20, 30, 20]