Python random() library
The Python random library is a built-in module that provides various functions for generating random numbers and performing related operations. This library is useful for a variety of applications such as generating random passwords, shuffling data, and simulating probabilistic events.
One of the most commonly used functions in the random library is random(), which returns a random floating point number in the range [0.0, 1.0). This function uses the Mersenne Twister pseudo-random number generator, which is a fast and widely used algorithm for generating high-quality pseudo-random numbers.
Get M Haque’s stories in your inbox
Join Medium for free to get updates from this writer.
Here is an example of how to use the random() function:
import random
# Generate a random float between 0 and 1
x = random.random()
print(x)Output:
0.23574927359346924The random() function can be used to generate random numbers in a specific range by multiplying the result by the desired range and then using the int() function to round down to the nearest integer. For example, to generate a random integer between 1 and 10, we can use the following code:
import random
# Generate a random integer between 1 and 10
x = int(random.random() * 10) + 1
print(x)Output:
5In addition to the random() function, the random library also provides a number of other useful functions for generating random numbers and shuffling data. Some of these functions include:
randint(a, b): Generates a random integer between a and b (inclusive).uniform(a, b): Generates a random float between a and b.shuffle(lst): Shuffles the elements of a list in place.sample(population, k): Returns a list of k random elements from the population.
Here is an example that demonstrates how to use some of these functions:
import random
# Generate a random integer between 1 and 10
x = random.randint(1, 10)
print(x)
# Generate a random float between 0 and 1
y = random.uniform(0, 1)
print(y)
# Shuffle a list
lst = [1, 2, 3, 4, 5]
random.shuffle(lst)
print(lst)
# Select 3 random elements from a list
lst = [1, 2, 3, 4, 5]
selected = random.sample(lst, 3)
print(selected)Output:
4
0.3548495739592476
[2, 3, 5, 4, 1]
[2, 3, 5]The random library is a powerful and convenient tool for generating random numbers and shuffling data in Python. Whether we are working on a project that requires randomization or simply want to add some randomness to your code, the random library has something to offer.





