Skip to main content

6.9) The Random Module


It can be handy to be able to generate a random number, for example to sample a mathematical distribution. In Python, you have to use the random module.

To use the module, you have to import it:

>>> import random

You can then use functions that are defined within the module (e.g. .random()) like this:

>>> x=random.random()

If you only want to use one function from a module, you can import only that specific function and you can avoid writing random. before the function name.

>>> from random import random  # which is: from module import function
>>> x=random()

The random module contains several useful functions:

>>> import random
>>> random.random()   # generates a random float in the range [0.0,1.0)
0.8114280822203986
>>> random.choice([1,2,3,4])  # randomly picks an element from a list
4
>>> random.randint(1,6)    # picks an integer in the range [1,6]
>>> L=[1,2,3,4,5,6,7,8,9,10]
>>> random.shuffle(L)      # shuffles an existing list
>>> print L                # note that L has been modified
[5, 9, 8, 7, 1, 4, 10, 6, 2, 3]