Python – Generate a random number

Table of Contents

Introduction

To generate a random number in Python you can use the random module.

In many cases it can be useful to know how to generate random numbers, think for example of a program that simulates a dice roll for statistical purposes.

Luckily, Python provides several methods for generating random numbers.
In this post we will see how to use the random module and some examples of use.

How to generate a random number in Python between 0 and 1

The basic functionality you can use is the random() method.
This method allows us to generate a random number between 0 and 1.

Its use is very simple, let’s see how to use it in this example:

import random
random_number = random.random()
print(random_number)

Output

0.1158682742815027

This code is quite straightforward, it simply uses the random function to generate a random number between 0 and 1.

If you repeat this code several times, the generated output will be always different.

Execution of several random numbers generation
Execution of several random numbers generation

How to generate a random number in a range in Python

In the previous section we have seen how to genereate a random number between 0 an 1, but how to use a different range?
Also in this case Python provides us with two methods to achieve our goal.
In the next chapters we will see how to use the uniform() and randrange() methods.

random.uniform(a,b)

The first Python method I want to introduce you to generate a random number in a range is uniform.
Using uniform function you can choose the range but remember, the result will be always a float number.

import random
# generate a random number bewteen 10 and 30
random_number = random.uniform(10, 30)
print(random_number)

Output

19.98978065463152

As you can see this command generated a random float number between 10 and 30.

random.randrange(start, stop[, step])

The second Python method I want to introduce you to is randrange.
it is quite similar to uniform seen in the previous chapter, but let’s see in detail how it is used.
randrange takes two parameters as input and returns a random integer.

Here an example:

import random
# generate a random number bewteen 10 and 30
random_number = random.randrange(10, 31)
print(random_number)

Output

27

Please note that the returned number is not a float like the other cases, but it is an integer and that the upper limit is not inclusive.
Indeed to generate a random number between 10 and 30 we need to use 10 and 31.

Generate a list of random numbers

In the previous chapters we have seen how it is possible to generate a random number and how to generate it between a range of values.
It may happen that in some applications you want to return a certain number of random numbers and perhaps save them in a Python list.

If you don’t know what a Python list is, check out this post!

Back to our topic, I want to show you a small piece of code to store multiple random numbers in a list.
Python doesn’t give us a method that returns a list of random numbers this time around, so we’ll do it.

In the code below we generate 10 random numbers and store them in a list using a for loop.
The random numbers are between 0 and 1.

import random
random_numbers_list = []
for i in range(10):
    random_numbers_list.append(random.random())
print(random_numbers_list)

Output

[
    0.4417978397617499, 0.8503475562767052, 0.9076880408916723, 0.3478745444272511, 0.798930033913547, 0.31536954901543124, 
    0.21430172365366318, 0.742072649496668, 0.9523878916474506, 0.27508925158450315
]

Of course you can use also the other method showed in this post, not only random().
In this way you can generate not only numbers between 0 and 1 but also in another range!

You need just to change the line number 5 with one of these:

random_numbers_list.append(random.random())
random_numbers_list.append(random.uniform(10, 30))
random_numbers_list.append(random.randrange(10, 31))

Extract random number from a sequence in Python

In the field of random number generation, you may want to randomly extract an element from a sequence.
Let’s take an example to understand better.
We have a list of objects and we want to draw one of them randomly.

For this kind of task the choice function is perfect!

import random
my_list = ["a", "b", "c", "d"]
# extract random choice from sequence
random_choice = random.choice(my_list)
print(random_choice)

Output

c

In this case, the choice function takes a list of strings as input and returns an element randomly.

Please remember that if the sequence is empty an IndexError exception is raised.
Check this example to understand better:

import random
my_list = []
# extract random choice from sequence
random_choice = random.choice(my_list)
print(random_choice)

Output

IndexError: Cannot choose from an empty sequence

Extract random element from empty list error
Extract random element from empty list error

It is possible to avoid this kind of error using a try-except statement.

import random
my_list = []
# extract random choice from sequence
try:
    random_choice = random.choice(my_list)
except IndexError as e:
    print("It is not possible to extract random element from empty list")

Another alternative that Python offers is the choices command which allows you to extract more than one number at a time.
Just pass another parameter called k.
This parameter is an integer and represents the number of random elements to be extracted.

import random
my_list = ["a", "b", "c", "d"]
# extract 3 random choices from sequence
random_choices_list = random.choices(my_list, k=3)
print(random_choices_list)

Output

['a', 'd', 'c']

How to shuffle list elements

Another very common task is having to shuffle items within a Python list.
Suppose you have a list with 5 elements and you need to change their position randomly.

Well, this goal is easily achieved with the shuffle() function.
Look at this example to clarify your ideas:

import random
my_list = ["a", "b", "c", "d", "e"]
# shuffle list elements
random.shuffle(my_list)
print(my_list)

Output

['b', 'e', 'a', 'd', 'c']

As you can see the shuffle function works “in place” in fact it doesn’t return anything, there is no need to assign any variable.

Conclusion

Here we are at the end of this post where we have seen how to generate a random number in Python and how to make random extractions from a sequence.
I hope everything is clear to you, but if not, feel free to contact me or write a comment below.
If, on the other hand, everything is clear to you, take a look at the latest posts!

Leave a Comment

Your email address will not be published. Required fields are marked *