Random number generation in programming has thousands of uses ranging from cryptography to game-development. Python supports random number generation with its built-in Random module.

In this tutorial, you’ll see how to generate different types of random numbers in Python. The process of randomly choosing an item from a Python list is also explained at the end of the tutorial along with a script that uses the Random module to randomly shuffle the order of items in a list.

The Random module in Python comes pre-installed with the default Python installation. To use the Random module, import it like we demonstrate below. After importing the random module, the following script calls the `dir()`

method to print the names of all the methods and attributes of the Random module.

```
import random
print(dir(random))
```

**Output:**

`['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']`

We’re going to dive deeper into some of these methods and see how they can be called to generate different styles of random numbers.

## Generate Random Numbers Between 0 and 1

Requesting random numbers between 0 and 1 is really common. The `random()`

method returns a random number between 0 (included) and 1 (not included). We can find out more about the `random()`

function by passing it to the `help()`

command in Python

`help(random.random)`

**Output:**

```
Help on built-in function random:
random() method of random.Random instance
random() -> x in the interval [0, 1).
```

The output shows that the method returns a value in the interval [0, 1). Here, the round bracket after 1 signifies that 1 is not included in the random numbers generated by the `random()`

method.

The following script generates 5 random numbers between 0 and 1.

```
for i in range(5):
rand_num = random.random()
print(rand_num)
```

**Output:**

```
0.5486183422034425
0.7305847722411378
0.5659219086519193
0.3578211188658361
0.16822115885603006
```

If we run the script above a second time, you’ll see 5 different numbers generated in the output.

```
for i in range(5):
rand_num = random.random()
print(rand_num)
```

**Output:**

```
0.11957209130893665
0.7142474917013404
0.18084006505984696
0.19900438096938133
0.04823446467719894
```

## Generate Random Numbers Within a Range

You can also generate random numbers within a range of numbers using the Python Random module. To do so, use the `uniform()`

method. You need to pass the lower limit and upper limit for the range as parameter values to the `uniform()`

method. For instance, the following script generates five random numbers between 2 and 8.

```
for i in range(5):
rand_num = random.uniform(2,8)
print(rand_num)
```

**Output:**

```
6.104003335206205
5.281189213098911
4.620178058260187
4.9089864579109594
7.651300431562037
```

Code More, Distract Less: Support Our Ad-Free Site

You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.

## Generate Random Numbers within a Normal Distribution

The `random()`

and `uniform()`

methods return a number selected randomly from a uniform distribution. To generate a random number within a normal or Gaussian distribution, use the `normalvariate()`

method.

Let’s print the help for the `normalvariate()`

method:

`help(random.normalvariate)`

**Output:**

```
Help on method normalvariate in module random:
normalvariate(mu, sigma) method of random.Random instance
Normal distribution.
mu is the mean, and sigma is the standard deviation.
```

To specify the normal distribution from which you want to generate a random number, you have to pass the mean value and the standard deviation value for the distribution, to the `normalvariate()`

method. For example, the following script generates 5 random numbers from a normal distribution with a mean of 0 and a standard deviation of 7.

```
for i in range(5):
rand_num = random.normalvariate(0,7)
print(rand_num)
```

**Output:**

```
8.50769914598948
-4.052105282635025
-5.038572230389826
-2.8022205914911087
6.251332322729557
```

The **68-95-99.7 rule**, or the empirical rule, can you help you remember that 68% of the values of a normal distribution will fall within 1 standard deviation of the mean, 95% will fall within 2 standard deviations and 99.7% will fall within 3 standard deviations.

You’re more than welcome to test this rule yourself using the following script, which runs one million random numbers across a normal distribution with a mean of 0 and a standard deviation of 7. It then checks whether the results are within one, two, or three standard deviations and prints the percentage of results that fell within each bin.

```
import random
sig1=0
sig2=0
sig3=0
meanX=0
sigmaX=7
N=1000000
for i in range(N):
rand_num = random.normalvariate(meanX,sigmaX)
if rand_num>=-sigmaX and rand_num<=sigmaX:
sig1=sig1+1
if rand_num>=-2*sigmaX and rand_num<=2*sigmaX:
sig2=sig2+1
if rand_num>=-3*sigmaX and rand_num<=3*sigmaX:
sig3=sig3+1
print("1 sigma: " + str(sig1/N*100) + "%")
print("2 sigma: " + str(sig2/N*100) + "%")
print("3 sigma: " + str(sig3/N*100) + "%")
```

Here’s the output I got:

```
1 sigma: 68.2921%
2 sigma: 95.4291%
3 sigma: 99.7231%
```

## Generate Random Integers

In addition to generating decimal numbers, you can generate integers using the Random module. To do so, call the `randint()`

method. Here’s what the `help()`

command returns for the `randint()`

method.

`help(random.randint)`

**Output:**

```
Help on method randint in module random:
randint(a, b) method of random.Random instance
Return random integer in range [a, b], including both end points.
```

You need to pass the lower bound and the upper bound for the interval from which you want to select a random number. The following script randomly returns 5 integers between 1 and 15.

```
for i in range(5):
rand_num = random.randint(1,15)
print(rand_num)
```

**Output:**

```
2
5
12
7
9
```

You can also define a step size for generating random integers between an interval. To do so, you need to call the `randrange()`

method and pass it three parameter values: the lower limit, the upper limit, and the step size. For instance, the `randrange()`

method in the following script will return a random number between 1 and 15, with a step size of 3, which means that the random numbers generated are forced to be 1, 1 + 3 = 4, 4 + 3 = 7, and so on.

```
for i in range(5):
rand_num = random.randrange(1,15,3)
print(rand_num)
```

**Output:**

```
1
10
13
7
13
```

## Generate a Set of Unique Random Numbers from a Collection

With the Random module, you can even generate a set of unique random numbers from any population sequence or set. The `sample()`

method from the Random module does that for you. The `help()`

command explains the functionality of the `sample()`

method as follows:

`help(random.sample)`

**Output:**

```
Help on method sample in module random:
sample(population, k) method of random.Random instance
Chooses k unique random elements from a population sequence or set.
```

The following script returns 5 random numbers between 0 and 9. Note that the range(10) function returns a sequence of items between 0 and 9. The `print`

command just prints the output to your screen so you can see the resulting set.

`print(random.sample(range(10), 5))`

**Output:**

`[8, 4, 2, 5, 6]`

Let’s see another example. Here we have our pre-defined dummy list with some decimal numbers and integers, and the `sample()`

method returns 3 random numbers from the list.

`print(random.sample([0.45,0.82,0.65,20,25], 3))`

**Output:**

`[20, 0.82, 0.65]`

It’s important to remember that the `sample()`

method returns a new set of unique numbers from your existing set.

## Select Random Items from a List

In addition to generating random numbers, the Random module also provides a method called `choice()`

which randomly selects an item from a list. The following script prints the result of the `help()`

command for the `choice()`

function.

`help(random.choice)`

**Output:**

```
Help on method choice in module random:
choice(seq) method of random.Random instance
Choose a random element from a non-empty sequence.
```

The following script randomly returns a string value from a list of 4 strings.

```
import random
colors = ["Red", "Green", "Blue", "Yellow"]
print(random.choice(colors))
```

The output shows that the string “yellow” is returned. If you execute the above script a couple more times, there’s a good chance different string values will be randomly chosen.

**Output:**

`Yellow`

## Randomly Shuffle Items in a List

Finally, you can change the order of items in a python list by randomly shuffling them using the `shuffle()`

method. The `shuffle()`

method shuffles a list in place, meaning your original list order is altered. The following script prints the items in a list before and after shuffling them using the `shuffle()`

method.

```
import random
colors = ["Red", "Green", "Blue", "Yellow"]
for c in colors:
print(c)
print("=========")
random.shuffle(colors)
for c in colors:
print(c)
```

**Output:**

```
Red
Green
Blue
Yellow
=========
Blue
Yellow
Red
Green
```

Code More, Distract Less: Support Our Ad-Free Site

You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.