The Python random module gives you a large number of functions for generate random numbers in various formats; from integers to floating point numbers to selecting items from lists.
Python random module: definition
The Python random module is a built-in library that allows you to generate random numbers and perform randomness-based operations in your programs. It includes several functions pseudo-random number generation which can be used in many application cases, from simulation to game development to encryption tasks.
Repeatability is an important feature of the random module. By setting an initial value or seedrandom generation can be reproduced. This is convenient for tests, experiments, and simulations requiring consistent random data.
List of functions of the random module
Python's random module contains several methods for generate and process random numbersThe following table gives an overview of the functions and their properties:
Function name | Definition |
---|---|
seed(a=None, version=2)
|
Sets 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 a k-bit integer. |
randrange(start, stop, step)
|
Generates 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)
|
Returns a list of k elements randomly chosen from the population; probabilities can be optionally specified. |
sample(k, population)
|
Creates a list of k randomly selected items from the population, without duplicates. |
shuffle(x)
|
Shuffles the elements of 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 bounds. |
triangular(bas, haut, mode)
|
Returns 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)
|
Returns 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)
|
Returns a random floating point number from a log normal distribution. |
normalvariate(mu, sigma)
|
Returns a random floating-point number from a normal distribution. |
vonmisesvariate(mu, kappa)
|
Returns a random floating-point number from a von Mises distribution. |
paretovariate(alpha)
|
Returns a random floating point number from a Pareto distribution. |
weibullvariate(alpha, beta)
|
Returns a random floating-point number from a Weibull distribution. |
Select random items from a list
If you want to select multiple items randomly from a list, you can use the function choices(seq, k=n)
from the Python random module, where n
is the number of random elements desired.
import random
ma_liste = ['Pomme', 'Banane', 'Orange', 'Fraise', 'Cerise']
# Sélection aléatoire d’un élément dans la liste
elements_aleatoires = random.choices(ma_liste, k=3)
print("Éléments sélectionnés aléatoirement :", elements_aleatoires)
python
In this case we use the function choices()
to select three random items from the list ma_liste
. The result is returned as a list of three random items.
Web hosting
Flexible, high-performance and secure web hosting
- SSL Certificate and DDoS Protection
- Data Backup and Restore
- 24/7 assistance and personal advisor
Mix a list
Function shuffle()
orders the elements of Python lists in random order.
import random
# Une liste d’éléments
ma_liste = ['Pomme', 'Banane', 'Orange', 'Fraise', 'Cerise']
# Mélanger les éléments de la liste
random.shuffle(ma_liste)
print("Liste mélangée :", ma_liste) # Exemple de sortie : Liste mélangée : ['Fraise', 'Banane', 'Pomme', 'Cerise', 'Orange']
python
You must keep in mind that shuffle()
modifies the list itself and does not return a new one. After applying shuffle()
the original list will be in random order.
Define a seed
If you use random.seed()
from Python's random module to define a specific seed valuethe random number generator will be launched when generating random numbers based on it. This means that setting the same seed value at a later time will generate the same set of random numbers in your application.
import random
# Définition de la valeur de la graine à 42
random.seed(42)
# Génération de nombres aléatoires
print(random.random()) # Exemple de sortie : 0.6394267984578837
print(random.random()) # Exemple de sortie : 0.025010755222666936
# Réinitialisation de la valeur de la graine à 42
random.seed(42)
# Génération à nouveau de nombres aléatoires
print(random.random()) # Exemple de sortie : 0.6394267984578837 (identique à la valeur précédente)
print(random.random()) # Exemple de sortie : 0.025010755222666936 (identique à la valeur précédente)
python
After setting the seed value, random numbers are generated and printed. If the seed value is set to the same valuethe same random numbers are generated again. In our example, the seed value is 42, which makes the random numbers reproducible as long as the seed value remains the same.