How to Generate Random Numbers in Python?

How to Generate Random Numbers in Python?

7 mins read33.6K Views Comment
clickHere
Updated on Jan 22, 2024 11:43 IST

In Data Science or Statistics, there are various instances where a programmer might need to work with random inputs. Python offers many predefined functions to generate and use random data.

2022_06_Random-Numbers-in-Python.jpg

In this article, we will guide you on how to generate random numbers of int and float types using Python. We will particularly focus on the random library in Python. So, without further ado, let’s get started! 

We will be covering the following sections today: 

Methods to Generate Random Numbers in Python  

The random module in Python contains pseudo-random number generators for various distributions: 

2022_06_image-237.jpg

Let’s see how each of the above methods works to generate random numbers: 

Generating a floating random number between 0 and 1 – random() 

One method is to use the random() function from the random module that generates a random float value in the range [0.0, 1.0], as shown: 


 
#Import the random library 
import random
n = random.random()
print(n)  
Copy code

Output:

2022_06_image-240.jpg

From nerd to expert ninja! Unlock Python on a deeper level and explore the best Python programmes from top colleges and online Python courses with our detailed guide.

What have we done here?  

  • We first import the random module of Python. 
  • Then, we call the random() method to get a random float between 0-1 and store it in the variable n
  • Print the randomly generated number. 

Generating a random integer within a given range – randint() 

The random module also provides a randint() method to generate an integer number within a specified range.  Let’s understand how to generate random number in Python with Range.

The function takes two numbers as arguments, [min, max] – defining the lower and upper limit of the range. Let’s look at the following example: 


 
#Import the random library 
import random
n = random.randint(40,100)
print(n)
Copy code

Output:

63

What have we done here?  

  • Firstly, import the random module of Python. 
  • Then, we call the randint(min, max) method to get a random integer within the given range and store it in the variable n
  • Print the randomly generated number. 

Generating a random integer list using for loop – randint() 

We can also use the randint() method of the random module to generate a list of integer numbers. For this, we use a for loop that iterates over a specified range.  

Let’s look at the following example: 


 
#Import the random library 
import random
rand_list =[]  
for i inrange(0,5):  
    n = random.randint(100,200)  
    rand_list.append(n)  
print(rand_list)
Copy code

Output:

[199, 107, 199, 103, 112]

What have we done here?  

  • Import the random module of Python. 
  • Declare an empty Python list variable rand_list
  • Then, use a for loop to iterate over a range that will determine the number of elements in the list.
  • Once the loop has completed its execution, print the randomly generated number list. 

Generating a sample of random integers within a given range – sample() 

The random module also provides a sample() method to generate a sampled list of random numbers within a specified range.  

Let’s understand through the following example: 


 
#Import the random library 
import random
n = random.sample(range(50,100),10)
print(n)
Copy code

Output:

[58, 56, 64, 54, 84, 50, 80, 89, 87, 55]

What have we done here?  

  • Import the random module of Python. 
  • Then, we simply call the sample() function that takes range(min, max) as one argument and the number of elements in the list as the other argument, which is 10 in this case
  • Finally, we print the sample of 10 randomly generated numbers between 50-100. 

Selecting a random number from a given list – choice() 

The random module provides another in-built method called choice() that returns a random element from a list, tuple, or string.  

Let’s look at the following example: 


 
#Import the random library 
import random
mylist =[1,3,5,7,9]
#Print a random number from the list
n = random.choice(mylist)
print(n)
Copy code

Output:

3

What have we done here?  

  • Import the random module of Python. 
  • Declare a variable mylist and initialize it with the given elements: [1, 3, 5, 7, 9] 
  • Then, we call the choice() function that takes the list variable as an argument and generates a random element from the specified list. 
 

Generating a random number from a list in the specified range – randrange() 

This random module method, called the randrange() function, generates a random number from a list obtained by start-stop skipping within a specified range.  

The function takes three arguments, [start(optional), stop, step(optional)] – defining the start and stop of the range. There is also a step parameter that determines the step point of the range.  

Let’s understand through the following example: 


 
#Import the random library 
import random
n = random.randrange(20,50,4)
print(n)
Copy code

Output:

44

What have we done here?  

  • Import the random module of Python. 
  • Then, we call the randrange() function, which takes the start=20, stop=50, and step=4 as parameters in this case
  • The function generates a random element from the list [24,28,32,36,40,44,48] that is obtained from the specified range.  

Generating a floating random number within a given range – uniform() 

The random module also provides a uniform() method to generate a random floating-point value within a specified range.  

The function takes two numbers as arguments, [x,y] – defining the lower and upper limit of the range. Let’s look at the following example: 


 
#Import the random library 
import random
n = random.uniform(13,17)
print(n)
Copy code

Output:

14.821073447519757

What have we done here?  

  • Import the random module of Python. 
  • Then, call the uniform(x,y) function to get a random float value within the given range and store it in the variable n
  • Print the randomly generated number. 

Generating a randomly shuffled list – shuffle() 

The random module has a shuffle() function that takes a Python list as an argument and shuffles the elements of the list in place to return None

Let’s understand through the following example: 


 
#Import the random library 
import random
mylist =[1,2,3,4,5,6,7]
#Print a random list
random.shuffle(mylist)
print(mylist)
Copy code
 

Output:

[3, 4, 5, 2, 1, 6, 7]

What have we done here?  

  • Import the random module of Python. 
  • Declare a variable mylist and initialize it with the given elements: [1,2,3,4,5,6,7] 
  • Then, we call the shuffle() function that takes the list variable as an argument and generates a shuffled list with the same elements.  
  • Print the list. 

Generating a floating random number sequence – seed() 

Lastly, the random module has a seed() function that can be used when you need to generate a sequence of random floating-point values. 

This function takes the seed value as an argument, initialising the pseudo-random number generator. Let’s understand through the following example: 


 
#Import the random library 
import random
#Specify seed
val =int(input("Enter seed value : "))
random.seed(val)
for i inrange(val):
    print(random.random(), end =' ')
Copy code

Output:

2022_06_image-242.jpg

What have we done here?  

  • Import the random module of Python. 
  • Take an integer input from the user as the seed value and store it in the variable val
  • Then, call the seed() function with the input seed value as the argument. 
  • Inside the function body, run a for loop, iterating it over the range of the seed value. 
  • Use the random() function to generate floating random numbers as specified by the seed value. For instance, in the above case, the given seed is 3, so a sequence of three floating-point values is printed. 

Endnotes 

This article discussed the most common methods in Python’s random module that can generate pseudo-random numbers. We learned how to generate random integers as well as random floating-point values. We also learned how to select random elements from a Python list. You can explore related articles here if you’d like to learn more about Python and practice Python programming. 

FAQs on How to Generate Random Numbers in Python

How do I generate a random integer within a specific range in Python?

You can use random.randint(a, b) to generate a random integer between a and b, inclusive. For example, random.randint(1, 10) will generate a random number between 1 and 10​.

Can I generate a random number that excludes the upper limit?

Yes, the random.randrange(start, stop) function generates a random number within the range [start, stop), excluding the stop value. For instance, random.randrange(1, 10) generates numbers between 1 and 9​.

How to generate random floating-point numbers?

Use random.uniform(x, y) for generating random floats in the range [x, y]. Additionally, random.random() gives a random float in the range [0.0, 1.0). The random.uniform() function is suitable for a specified range, whereas random.random() is for the standard range of 0 to 1​.

Is there a way to choose a random element from a list?

Yes, the random.choice(sequence) function selects a random element from a non-empty sequence like a list or a tuple. For example, if you have a list [1, 2, 3, 4, 5], random.choice() can randomly pick any element from this list​.

How can I generate a list of unique random numbers?

Use random.sample(population, k) to get a list of unique elements sampled from the population. The length of the list will be k. This is useful for scenarios where you need several different random elements from a sequence​.

What function should I use for cryptographic purposes or secure random number generation?

The secrets module is designed for cryptographic purposes and provides functions like secrets.randbelow(n), which generates a secure random number less than n.​

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio

Comments