The Wayback Machine - https://web.archive.org/web/20240524235948/https://www.geeksforgeeks.org/python-random-module/
Open In App

Python Random Module

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python Random module generates random numbers in Python. These are pseudo-random numbers means they are not truly random.

This module can be used to perform random actions such as generating random numbers, printing random a value for a list or string, etc. It is an in-built function in Python.

List of all the functions  Python Random Module

There are different random functions in the Random Module of Python. Look at the table below to learn more about these functions:

Function Name

Description

seed() Initialize the random number generator
getstate() Returns an object with the current internal state of the random number generator
setstate() Used to restore the state of the random number generator back to the specified state
getrandbits() Return an integer with a specified number of bits
randrange() Returns a random number within the range
randint() Returns a random integer within the range
choice() Returns a random item from a list, tuple, or string
choices() Returns multiple random elements from the list with replacement
sample() Returns a particular length list of items chosen from the sequence
random() Generate random floating numbers
uniform() Return a random floating number between two numbers both inclusive
triangular() Return a random floating point number within a range with a bias towards one extreme
betavariate() Return a random floating point number with beta distribution
expovariate() Return a random floating point number with exponential distribution
gammavariate() Return a random floating point number with a gamma distribution
gauss() Return a random floating point number with Gaussian distribution
lognormvariate() Return a random floating point number with a log-normal distribution
normalvariate() Return a random floating point number with normal distribution
vonmisesvariate() Return a random floating point number with von Mises distribution or circular normal distribution
paretovariate() Return a random floating point number with a Pareto distribution
weibullvariate() Return a random floating point number with Weibull distribution

Random Module in Python Examples

Let’s discuss some common operations performed by Random module in Python.

Example 1: Printing a random value from a list in Python.

This code uses the random module to select a random element from the list list1 using the random.choice() function. It prints a random element from the list, demonstrating how to pick a random item from a sequence in Python.

Python3




import random
list1 = [1, 2, 3, 4, 5, 6]
print(random.choice(list1))


Output

3

Example 2: Creating random numbers with Python seed() in Python.

As stated above random module creates pseudo-random numbers. Random numbers depend on the seeding value. For example, if the seeding value is 5 then the output of the below program will always be the same. Therefore, it must not be used for encryption.

The code sets the random number generator’s seed to 5 using random.seed(5), ensuring reproducibility. It then prints two random floating-point numbers between 0 and 1 using random.random(). The seed makes these numbers the same every time you run the code with a seed of 5, providing consistency in the generated random values.

Python3




import random
random.seed(5)
print(random.random())
print(random.random())


Output

0.6229016948897019
0.7417869892607294

Generate Random Numbers in Python

random.randint() method is used to generate random integers between the given range.

Syntax: randint(start, end)

Example: Creating random integers

This code uses the ‘random' module to generate random integers within specific ranges. It first generates a random integer between 5 and 15 (inclusive) and then between -10 and -2 (inclusive). The generated integers are printed with appropriate formatting.

Python3




import random
r1 = random.randint(5, 15)
print("Random number between 5 and 15 is % s" % (r1))
r2 = random.randint(-10, -2)
print("Random number between -10 and -2 is % d" % (r2))


Output

Random number between 5 and 15 is 10
Random number between -10 and -2 is -2

Generate Random Float numbers in Python

A random.random() method is used to generate random floats between 0.0 to 1.

Syntax: random.random()

Example:

In this code, we are using the random function from the ‘random' module in Python. It prints a random floating-point number between 0 and 1 when you call random().

Python3




from random import random
print(random())


Output

0.8443722499369146

Randomly Select Elements from a List in Python

Random sampling from a list in Python (random.choice, and sample)

Example 1:  Python random.choice() function is used to return a random item from a list, tuple, or string.

The code uses the random.choice() function from the random module to randomly select elements from different data types. It demonstrates selecting a random element from a list, a string, and a tuple. The chosen elements will vary each time you run the code, making it useful for random selection from various data structures.

Python3




import random
list1 = [1, 2, 3, 4, 5, 6]
print(random.choice(list1))
string = "geeks"
print(random.choice(string))
tuple1 = (1, 2, 3, 4, 5)
print(random.choice(tuple1))


Output

4
k
5

Example 2:  Python random.sample() function is used to return a random item from a list, tuple, or string.

Syntax: random.sample(sequence, length)

This code utilizes the sample function from the ‘random' module to obtain random samples from various data types. It selects three random elements without replacement from a list, a tuple, and a string, demonstrating its versatility in generating distinct random samples. With each execution, the selected elements will differ, providing random subsets from the input data structures.

Python3




from random import sample
list1 = [1, 2, 3, 4, 5]
 
print(sample(list1,3))
list2 = (4, 5, 6, 7, 8)
 
print(sample(list2,3))
list3 = "45678"
 
print(sample(list3,3))


Output

[4, 2, 3]
[4, 7, 8]
['6', '4', '8']

Shuffle List in Python

A random.shuffle() method is used to shuffle a sequence (list). Shuffling means changing the position of the elements of the sequence. Here, the shuffling operation is inplace.

Syntax: random.shuffle(sequence, function)

Example: Shuffling a List

This code uses the random.shuffle() function from the ‘random' module to shuffle the elements of a list named ‘sample_list'. It first prints the original order of the list, then shuffles it twice. The second shuffle creates a new random order, and the list’s content is displayed after each shuffle. This demonstrates how the elements are rearranged randomly in the list with each shuffle operation.

Python3




import random
sample_list = [1, 2, 3, 4, 5]
 
print("Original list : ")
print(sample_list)
random.shuffle(sample_list)
print("\nAfter the first shuffle : ")
print(sample_list)
random.shuffle(sample_list)
print("\nAfter the second shuffle : ")
print(sample_list)


Output

Original list : 
[1, 2, 3, 4, 5]

After the first shuffle : 
[3, 2, 1, 5, 4]

After the second shuffle : 
[2, 3, 1, 5, 4]

In this article we discussed about Python Random module, and also saw some examples of functions in random module in Python. Random module in Python is very important and contains very useful functions.

Hope this helps you in using Python Random module functions.

More on Python Modules:



Similar Reads

Os Module Vs. Sys Module In Python
Python provides a lot of libraries to interact with the development environment. If you need help using the OS and Sys Module in Python, you have landed in the right place. This article covers a detailed explanation of the OS and Sys Module including their comparison. By the end of this article, you will be able to easily decide which module suits
5 min read
uniform() method in Python Random module
uniform() is a method specified in the random library in Python 3. Nowadays, in general, day-day tasks, there's always the need to generate random numbers in a range. Normal programming constructs require a method more than just one word to achieve this particular task. In python, there's an inbuilt method, "uniform()" which performs this task with
2 min read
Python Random - random() Function
There are certain situations that involve games or simulations which work on a non-deterministic approach. In these types of situations, random numbers are extensively used in the following applications: Creating pseudo-random numbers on Lottery scratch cardsreCAPTCHA on login forms uses a random number generator to define different numbers and ima
3 min read
Random sampling in numpy | random() function
numpy.random.random() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random floats in the half-open interval [0.0, 1.0). Syntax : numpy.random.random(size=None) Parameters : size : [int or tuple of ints, optional] Output shape. If the given shape is, e.g., (m, n, k), then m * n *
2 min read
NumPy random.noncentral_f() | Get Random Samples from noncentral F distribution
The NumPy random.noncentral_f() method returns the random samples from the noncentral F distribution. Example C/C++ Code import numpy as np import matplotlib.pyplot as plt gfg = np.random.noncentral_f(1.24, 21, 3, 1000) count, bins, ignored = plt.hist(gfg, 50, density = True) plt.show() Output: Syntax Syntax: numpy.random.noncentral_f(dfnum, dfden,
1 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Python calendar module : formatmonth() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. class calendar.TextCalendar(firstweekday=0) can be used to generate plain text
2 min read
Python | Writing to an excel file using openpyxl module
Prerequisite : Reading an excel file using openpyxl Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files. For example, user might have to go through thousands of rows and pick out few handful information to make small changes b
3 min read
median() function in Python statistics module
Python is a very popular language when it comes to data analysis and statistics. Luckily, Python3 provide statistics module, which comes with very useful functions like mean(), median(), mode() etc.median() function in the statistics module can be used to calculate median value from an unsorted data-list. The biggest advantage of using median() fun
4 min read
Article Tags :
Practice Tags :