In this article, We will learn how to generate random numbers and data in Python using a random module. In Python, a random module implements pseudo-random number generators for various distributions including integer, float (real).
The Goals of this article: –
The following are the list of common operations that we are going to cover in this article.
- Generate random numbers for various distributions including integer and floats.
- Random Sampling and choose elements from the population.
- Functions of the random module.
- Shuffle the sequence data. Seed the random generator.
- Generate random strings and passwords.
- Cryptographically secure random generator using a secrets module. Generate secure tokens, security keys, and URL
- How to set the state of a random generator.
- Use NumPy’s random to generate random arrays.
- Use the UUID module to generate unique IDs
The article links provided in this article is also written by me to cover subtopic in detail.
How to Use a random module
The random module has various functions to accomplish all of the above tasks. We will see how to use these functions in the latter section of the article.
You need to import the random module in your program, and you are ready to use this module. Use the following statement to import the random module in your code.
Let see how to use a random module now.
import random print("Printing random number using random.random()") print(random.random())
Printing random number using random.random() 0.5015127958234789
As you can see we have got 0.50. You may get a different number.
random()is the most basic function of the random module.
- Almost all functions of the random module depend on the basic function random().
random()return the next random floating-point number in the range [0.0, 1.0).
random module functions
Now let see the different functions available in the random module and their usage.
random.randint() to generate a random integer number within a range. Let’s see the example to generate a random number between 0 and 9.
import random print("Random integer is", random.randint(0, 9))
Random integer is 7
random.randrange(start, stop [, step])
This function returns a randomly selected integer from
range(start, stop, step). Use this function to generate a random integer number within a range. For example,
random.randrange(2, 20, 2) will return any random number between 2 to 20, such as 2, 4, 6, …18.
import random print("Random integer is", random.randrange(2, 20, 2))
Random integer is 14
random.choice function to randomly select an item from a List or any sequence.
import random city_list = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Philadelphia'] print("Random element from list:", random.choice(city_list))
Random element from the list: Chicago
Use this function when you want to pick multiple elements from a list or any sequence randomly.
import random city_list = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Philadelphia'] print("Pick 2 Random element from list:", random.sample(city_list, 2))
Pick 2 Random element from list: ['Philadelphia', 'Los Angeles']
random.choices(population, weights=None, *, cum_weights=None, k=1)
When you want to choose more than one element from the sequence randomly, then use this method. Choices method introduced in python version 3.6 and it can repeat the elements. It is a random sample with replacement.
import random #sampling with replacement list = [20, 30, 40, 50 ,60, 70, 80, 90] sampling = random.choices(list, k=5) print("sampling with choices method ", sampling)
sampling with choices method [90, 50, 40, 60, 40]
random.choices() is mainly used to implement weighted random choices so that we can choose elements from the list with different probabilities
The seed function is used to initialize the pseudorandom number generator in Python. The random module uses the seed value as a base to generate a random number. If seed value is not present, it takes a system current time. If you use the same seed value before calling any random module function, you will get the same output every time.
import random # Random number with seed 6 random.seed(6) print(random.randint(10, 20)) random.seed(6) print(random.randint(10, 20))
Use this function to shuffle or randomize a list or other sequence types. The
shuffle function shuffles a list in-place. The most common example is shuffling cards.
list = [2,5,8,9,12] random.shuffle(list) print ("Printing shuffled list ", list)
Printing shuffled list [5, 9, 12, 2, 8]
random.uniform() to generate a floating-point number within a range.
import random print("floating point within given range") print(random.uniform(10.5, 25.5))
floating point within given range 16.76682097326141
random.triangular(low, high, mode)
random.triangular() function returns a random floating-point number N such that
lower <= N <= upper and with the specified mode between those bounds.
The default value of a lower bound is ZERO, and upper bounds are one. Moreover, the peak argument defaults to the midpoint between the bounds, giving a symmetric distribution.
random.triangular() function to generate random numbers for triangular distribution to use these number in a simulation. i.e., to generate value from a triangular probability distribution.
import random print("floating point triangular") print(random.triangular(10.5, 25.5, 5.5))
floating point triangular 16.114862085401924
Generate random String
In this section, I will let you know how to generate a random string of a fixed length in python.
Refer our guide to Generate the random string in Python.
This guide includes the following things: –
- Generate random the string of fixed length.
- Get the random alphanumeric string with letters and digits.
- Generate the random password which contains the letters, digits and special symbols.
Cryptographically secure random generator in Python
Random Numbers and data generated by the random module are not cryptographically secure. So How to generate a random number that is cryptographically secure in Python?
cryptographically secure pseudo-random number generator is a random number generator which has the properties that make it suitable for use in cryptography application where data security is essential.
- All cryptographically secure random generator function returns random bytes.
- Random bytes returned by this function depend on the random sources of the OS. Quality of randomness depends on randoms sources of the OS.
We can use the following approaches to secure the random generator in Python cryptographically
- The secrets module to secure random data
- Use the os.urandom()
- use random.SystemRandom class
import random import secrets number = random.SystemRandom().random() print("secure number is ", number) print("Secure byte token", secrets.token_bytes(16))
secure number is 0.11139538267693572 Secure byte token b'\xae\xa0\x91*.\xb6\xa1\x05=\xf7+>\r;Y\xc3'
Refer our guides which cover the above topic in detail.
Get and Set the state of random Generator
The random module has two function getstate and setstate which helps us to capture the current internal state of the random generator. Using this state, we can generate the same random numbers or sequence of data.
getstate function returns an object by captures the current internal state of the random generator. We can pass this state to the
setstate method to restore this state as a current state.
setstate() function restores the internal state of the generator to the state object. i.e. it applies the same state again. This state object can be obtained by calling the
Why Use getstate and setstate functions
If you get a previous state and restore it, then you can reproduce the same random data again and again. Remember you cannot use a different random function, nor you can change parameters value. By doing this, you are altering the state.
Let see the example now to have a clear understanding of how to get and set the random generator in Python.
import random number_list = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30] print("First Sample is ", random.sample(number_list,k=5)) state = random.getstate() # store this current state in state object print("Second Sample is ", random.sample(number_list,k=5)) random.setstate(state) # restore state now using setstate print("Third Sample is ", random.sample(number_list,k=5)) #Now it will print the same second sample list random.setstate(state) # restore state now print("Fourth Sample is ", random.sample(number_list,k=5)) #again it will print the same second sample list again
First Sample is [18, 15, 30, 9, 6] Second Sample is [27, 15, 12, 9, 6] Third Sample is [27, 15, 12, 9, 6] Fourth Sample is [27, 15, 12, 9, 6]
As you can see in the output, we are getting same sample list because resetting the random generator.
Numpy.random – PRNGs for Arrays
PRNG is an acronym for pseudorandom number generator. As you know using the Python random module, we can generate scalar random numbers and data.
- Whenever you want to generate an array of random numbers you need to use
- numpy has the
numpy.randompackage which has multiple functions to generate the random n-dimensional array for various distributions.
Now, Let see some examples.
Generate a random n-dimensional array of float numbers
numpy.random.rand()to generate an n-dimensional array of random float numbers in the range of [0.0, 1.0)
numpy.random.uniformto generate an n-dimensional array of random float numbers in the range of [low, high)
import numpy random_float_array = numpy.random.rand(2, 2) print("2 X 2 random float array in [0.0, 1.0] \n", random_float_array,"\n") random_float_array = numpy.random.uniform(25.5, 99.5, size=(3, 2)) print("3 X 2 random float array in range [25.5, 99.5] \n", random_float_array,"\n")
random float array in [0.0, 1.0] [[0.99158699 0.02109459] [0.41824566 0.66862725]] random float array in [25.5, 99.5] [[93.061888 86.81456246] [76.19239634 50.39694693] [82.25922559 78.63936106]]
Generate a random n-dimensional array of Integers numbers
numpy.random.random_integers()to generate a random n-dimensional array of integers.
import numpy random_integer_array = numpy.random.random_integers(1, 10, 5) print("1-dimensional random integer array \n", random_integer_array,"\n") random_integer_array = numpy.random.random_integers(1, 10, size=(3, 2)) print("2-dimensional random integer array \n", random_integer_array)
1-dimensional random integer array [10 1 4 2 1] 2-dimensional random integer array [[ 2 6] [ 9 10] [ 3 6]]
Choose the random element from the array of numbers or sequence
- Use the
numpy.random.choice()to generate the random samples.
- Use this method to get single or multiple random numbers from the n-dimensional array with or without replacement.
Let see the examples now.
import numpy array =[10, 20, 30, 40, 50, 20, 40] single_random_choice = numpy.random.choice(array, size=1) print("single random choice from 1-D array", single_random_choice) multiple_random_choice = numpy.random.choice(array, size=3, replace=False) print("multiple random choice from 1-D array without replacement ", multiple_random_choice) multiple_random_choice = numpy.random.choice(array, size=3, replace=True) print("multiple random choice from 1-D array with replacement ", multiple_random_choice)
single random choice from 1-D array  multiple random choices from the 1-D array without replacement [20 20 10] multiple random choices from the 1-D array with replacement [10 50 50]
We will cover other numpy’ s random package functions and their use in the upcoming articles.
Generate random Universally unique IDs
Python UUID Module provides immutable UUID objects. UUID is a Universally Unique IDentifier.
It has the functions to generate all versions of UUID. Using
uuid.uuid4() function, you can generate a 128 bit long random unique ID ad it’s cryptographically safe.
These unique Ids are used to identify the documents, Users, resources or any information in computer systems. Learn more on the UUID module.
import uuid # get a random UUID safeId = uuid.uuid4() print("safe unique id is ", safeId)
safe unique id is UUID('78mo4506-8btg-345b-52kn-8c7fraga847da')
Dice Game Using a Random module
I have created a simple dice game to understand random module functions. In this game, we have two players and two dice.
- One by one each player shuffle both the dice and play.
- The algorithm calculates the sum of two dice number and adds it to each player’s scoreboard.
- The Player who scores high number is the winner.
import random PlayerOne = "Eric" PlayerTwo = "Kelly" EricScore = 0 KellyScore = 0 # each dice contains six numbers diceOne = [1, 2, 3, 4, 5, 6] diceTwo = [1, 2, 3, 4, 5, 6] def playDiceGame(): """#Both Eric and Kelly will roll both the dices using shuffle method""" for i in range(5): #shuffle both the dice 5 times random.shuffle(diceOne) random.shuffle(diceTwo) firstNumber = random.choice(diceOne) # use choice method to pick one number randomly SecondNumber = random.choice(diceTwo) return firstNumber + SecondNumber print("Dice game using a random module\n") #Let's play Dice game three times for i in range(3): # let's do toss to determine who has the right to play first EricTossNumber = random.randint(1, 100) # generate random number from 1 to 100. including 100 KellyTossNumber = random.randrange(1, 101, 1) # generate random number from 1 to 100. dosen't including 101 if( EricTossNumber > KellyTossNumber): print("Eric won the toss") EricScore = playDiceGame() KellyScore = playDiceGame() else: print("Kelly won the toss") KellyScore = playDiceGame() EricScore = playDiceGame() if(EricScore > KellyScore): print ("Eric is winner of dice game. Eric's Score is:", EricScore, "Kelly's score is:", KellyScore, "\n") else: print("Kelly is winner of dice game. Kelly's Score is:", KellyScore, "Eric's score is:", EricScore, "\n")
Dice game using a random module Kelly won the toss Eric is the winner of a dice game. Eric's Score is: 9 Kelly's score is: 6 Kelly won the toss Eric is the winner of a dice game. Eric's Score is: 11 Kelly's score is: 9 Eric won the toss Kelly is the winner of a dice game. Kelly's Score is: 12 Eric's score is: 5
To practice what you learned in this tutorial, I have created a Quiz and Exercise project.
That’s it. Folks Let me know your comments in the section below.