In this article, We will learn how to** generate random numbers and data in Python using a random module and other available modules**. In Python, random module implements pseudo-random number generators for various distributions including integer, float (real).

- Solve our
**Python random data generation Exercise.** **And Python Random data generation Quiz**to master random data generation techniques.

**The Goals of this article: –**

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**password**. **Cryptographically secure**random generator using**secrets module.**Generate secure**tokens**, security**keys**, and**URL**- How to
**set the state of a random generator**. - Use
**numpy.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 in Python

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.

import random

Let see how to use random module now.

import random print("Printing random number using random.random()") print(random.random())

**Output**: **Execute Online**

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).

**Before moving to the random module functions, let see the common uses cases first.**

## Generate Random Numbers

Let see the most common use of the random module. I.e., generate a random number. Use randint () function to generate a random integer number in Python.

To generate random integers, we can use the following two functions.

**randint**()**randrange**()

* The following example generates a random number between 0 and 9*.

from random import randint print("Printing random integer ", randint(0, 9)) print("Printing random integer ", randrange(0, 10, 2))

Output:

Printing random integer 2 Printing random integer 6

We will see various ways of generating the random number in Python in the latter section of this article.

## Randomly select an item from a List

Assume you have the following list of cities and you want to retrieve an item at random from this list. Let see how to do this.

import random city_list = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Philadelphia'] print("Select random element from list - ", random.choice(city_list))

Output: **Execute Online**

Select random element from the list - Chicago

## Python random module Functions

Now let see the different functions available in the random module.

### random.randint(a, b)

- Return a random integer
`Number`

such that`a <= Number <= b`

. - A
`randint(a,b)`

works only for integers. - The
`randint(a,b)`

function accepts two parameters, and both are required. - The resultant random number is greater than or equal to
`a`

and less than or equal to`b`

.

Example: –

import random print("Use random.randint() to Generate random integer") print(random.randint(0, 5)) print(random.randint(0, 5))

Output:

Use random.randint() to Generate random integer 3 1

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

Use this method **to generate a random integer number within a given range**. For Example, generate a random number between 10 to 50.

The step is a difference between each number in the sequence. The step is optional, and the default value of the step is 1.

Example: –

import random print("Generate random integer number within a given range") print(random.randrange(10, 50, 5)) print(random.randrange(10, 50, 5))

Output:

Generate random integer number within a given range 20 35

**Refer our complete guide on randrange () in Python.**

### random.choice(seq)

Use the `random.choice`

method to **pick a random element from the sequence**. Here sequence can be list or string. This method returns a single item from the sequence.

Example:

list = [55, 66, 77, 88, 99] print("random.choice to select a random element from a list - ", random.choice(list))

Output: **Execute Online**

random.choice to select a random element from a list 77

**Refer our complete guide on random.choice() in Python.**

### random.sample(population, k)

Use this method **when we want to pick more multiple random elements from a population**.

- Sample method returns a list of unique elements chosen from the population. Count of the total elements depends on the size of k.
- The population can be the list, set or any sequence.

Example: –

import random list = [2,5,8,9,12] print ("random.sample() ",random.sample(list,3))

Output: **Execute Online**

random.sample() [2, 9, 5]

**Refer our complete guide on random.sample () in Python.**

### random.choices()

`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.

Examples: –

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)

Output: **Execute Online**

sampling with choices method [90, 50, 40, 60, 40]

### random.seed(a=None, version=2)

- The seed method 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.

Example:

import random random.seed(6) print("Random number with seed ",random.random()) random.seed(6) print("Random number with seed ",random.random())

Output: **Execute Online**

Random number with seed 0.793340083761663 Random number with seed 0.793340083761663

**Refer our complete guide on random.seed () in Python.**

### random.shuffle(x[, random])

To shuffle or randomize list or other sequence types. The `shuffle`

function shuffles a list in-place. The most common example is shuffle cards.

Example:

list = [2,5,8,9,12] random.shuffle(list) print ("Printing shuffled list ", list)

Output: **Execute Online**

Printing shuffled list [5, 9, 12, 2, 8]

**Refer our complete guide on random.shuffle () in Python.**

### random.uniform(start, end)

- Use
`random.uniform()`

to**generate a floating point number within a given range**. - The end-point value may or may not be included in the range depending on floating-point rounding.
- For example, Generate random float number between 10.5 to 25.5.

Example: –

import random print("floating point within given range") print(random.uniform(10.5, 25.5))

Output: **Execute Online**

floating point within given range 16.76682097326141

**Refer our complete guide to Generate random float numbers in Python****.**

### random.triangular(low, high, mode)

The `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.

Use the `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.

Example:

import random print("floating point triangular") print(random.triangular(10.5, 25.5, 5.5))

Output: **Execute Online**

floating point triangular 16.114862085401924

**Free random data generation Exercise**to master random data generation techniques in Python.

## 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

Example:

import random import secrets number = random.SystemRandom().random() print("secure number is ", number) print("Secure byte token", secrets.token_bytes(16))

Output:

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 python 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.

### random.getstate()

The `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.

### random.setstate(state)

The `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 `getstate`

function.

### 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 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 on 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

Output: **Execute Online**

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.

**Free random data generation Exercise**to master random data generation techniques in Python.

## 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.random`

. - numpy has the
for various distributions.`numpy.random`

package which has multiple functions to generate the random n-dimensional array

Now, Let see some examples.

### Generate a random n-dimensional array of float numbers

- Use
to generate an n-dimensional array of random float numbers in the range of [0.0, 1.0)`numpy.random.rand()`

- Use
to generate an n-dimensional array of random float numbers in the range of [low, high)`numpy.random.uniform`

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")

Output: **Execute Online**

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

use the ** 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)

Output: **Execute Online**

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
to generate the random samples.`numpy.random.choice()`

- 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)

Output: **Execute Online**

single random choice from 1-D array [10] 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**.

**Example**:

import uuid # get a random UUID safeId = uuid.uuid4() print("safe unique id is ", safeId)

**Output**:

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**.

**Program**:

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")

**Output**: **Execute Online**

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

Reference: –

## Next Steps

To practice what you learned in this tutorial, I have created a Python random data generation Quiz and Exercise project.

- Solve our
**Python Random data generation Quiz**to test your random data generation concepts. - Also, Solve the
**Python random data generation Exercise**to practice and master the random data generation techniques.

That’s it. Folks Let me know your comments in the section below.

Robert Basham

Very nice presentation, thanks.

You might mention that random() uses Mersenne Twister as the core generator and that it produces 53-bit precision floats with a period of 2**19937-1. Also, that it is not designed for cryptographic uses.

Vishal

Thank you Robert Basham

Muhammad Jawad

i create a random list an python and after that i want that list in csv file but i can’t can you help me please