How to use the Python random module

The Python random module offers you a variety of functions for generating random numbers in various formats, ranging from integers to floating-point numbers to selecting elements from lists.

What is Python’s random module and what can it be used for?

The Python random module random is a built-in library that allows you to generate random numbers and perform random-based operations in your programs. It includes various functions for generating pseudo-random numbers that can be used in many applications, from simulation to game development and cryptographic tasks.

An important characteristic of the random module is its ability to provide reproducible results. By establishing a starting value or seed, the process of random generation can be reproduced. This is beneficial for testing, experiments and simulations that require consistent random data.

What are the functions in the random module?

The Python random module contains various methods for generating and processing random numbers. The following table provides an overview of the functions and their properties:

Name of function Explanation
seed(a=None, version=2) Defines the initial value (seed) for the random number generator
getstate() Returns the current state of the random number generator as an object
setstate(state) Resets the state of the random number generator using a state object
getrandbits(k) Returns an integer with k bits
randrange(start, stop, step) Creates a random integer from the specified range
randint(a, b) Returns a random integer in the specified range
choice(seq) Returns a random element from the given sequence
choices(population, weights=None, *, cum_weights=None, k=1) Creates a list with k randomly selected elements from the population; optional to specify the probabilities
sample(k, population) Creates a list with k randomly selected elements from the population, without duplicates
shuffle(x) Shuffles the elements in a list in random order
random() Returns a random floating-point number between 0 and 1
uniform(a, b) Returns a random floating-point number in the specified range, including the limit values
triangular(low, high, mode) Creates a random floating-point number in the triangular distribution range
betavariate(alpha, beta) Returns a random floating-point number from a beta distribution
expovariate(lambd) Returns a random floating-point number from an exponential distribution
gammavariate(alpha, beta) Creates a random floating-point number from a gamma distribution
gauss(mu, sigma) Returns a random floating-point number from a Gaussian distribution
lognormvariate(mu, sigma) Creates a random floating-point number from a logarithmic normal distribution
normalvariate(mu, sigma) Returns a random floating-point number from a normal distribution
vonmisesvariate(mu, kappa) Returns a random floating-point number with a von Mises distribution or circular normal distribution
paretovariate(alpha) Returns a random floating-point number with a Pareto distribution
weibullvariate(alpha, beta) Returns a random floating-point number with a Weibull distribution

How to select elements randomly from a list

If you want to select several random elements from a list, you can use the function choices(seq, k=n) from the Python random module, where n is the number of desired random elements.

import random
my_list = ['Apple', 'Banana', 'Orange', 'Strawberry', 'Cherry']
# Randomly selecting an element from the list
random_elements = random.choices(my_list, k=3)
print("Randomly selected elements:", random_elements)
python

In this case, we use the choices() function to select three random elements from my_list. The results are returned as a list of three random elements.

Web Hosting
Secure, reliable hosting for your website
  • 99.9% uptime and super-fast loading
  • Advanced security features
  • Domain and email included

How to shuffle a list

The shuffle() function arranges Python list elements in a random order.

import random
# A list of elements
my_list = ['Apple', 'Banana', 'Orange', 'Strawberry', 'Cherry']
# Shuffle the elements in the list
random.shuffle(my_list)
print("Shuffled list:", my_list) # Example Output: Shuffled list: ['Strawberry', 'Banana', 'Apple', 'Cherry', 'Orange']
python

You should keep in mind that shuffle() changes the list itself and does not return a new one. After using shuffle(), the original list will be in a random order.

How to set a seed value

When you use random.seed() from the Python random module to set a specific seed value, it initialises the random number generator to produce random numbers using this seed. Therefore, if you set the same seed value again later, it will result in the identical sequence of random numbers being generated in your application.

import random
# Setting the seed value to 42
random.seed(42)
# Generating random numbers
print(random.random())  # Example output: 0.6394267984578837
print(random.random())  # Example output: 0.025010755222666936
# Resetting the seed value to 42
random.seed(42)
# Generating random numbers again
print(random.random())  # Example output: 0.6394267984578837 (identical to the previous value)
print(random.random())  # Example output: 0.025010755222666936 (identical to the previous value)
python

After the seed value is set, it generates and outputs random numbers. Resetting the seed to the same value results in the same sequence of random numbers being produced again. In this example, the seed value is 42. As long as this seed remains constant, the random numbers can be consistently replicated.

Was this article helpful?
Page top