π² Random Module: import random
The random module in Python is a built-in library designed to generate pseudo-random numbers for various applications such as simulations, games, and data sampling. It offers a wide range of functions to produce random numbers, select random elements, and work with different probability distributions. However, itβs important to note that the randomness provided by this module is not suitable for cryptographic purposes.
- use
import randomto access the moduleβs functions. - use
print(help(random))to see the documentation and available functions.
βοΈ Methods and Functions
random.random(): Returns a random float between 0.0 and 1.0.random.randint(a, b): Returns a random integer N such thata <= N <= b.random.choice(seq): Returns a randomly selected element from a non-empty sequence (like a list or tuple).random.shuffle(x): Shuffles the elements of a list in place.random.sample(population, k): Returns a list ofkunique elements chosen from the population sequence.random.uniform(a, b): Returns a random float N such thata <= N <= b.random.gauss(mu, sigma): Returns a random float from a Gaussian distribution with meanmuand standard deviationsigma.random.seed(a=None): Initializes the random number generator with a seed value for reproducibility.
π‘ Example Usage
random_example.py
import random
# Generate a random float between 0.0 and 1.0
random_float = random.random()
print(f"Random float: {random_float}")
# Generate a random integer between 1 and 10
random_int = random.randint(1, 10)
print(f"Random integer: {random_int}")
# Select a random element from a list
my_list = [1, 2, 3, 4, 5]
random_choice = random.choice(my_list)
print(f"Random choice from list: {random_choice}")
# Shuffle a list in place
random.shuffle(my_list)
print(f"Shuffled list: {my_list}")
# Generate a sample of 3 unique elements from a list
sample_list = random.sample(my_list, 3)
print(f"Sample of 3 unique elements: {sample_list}")
# Generate a random float between 1.0 and 10.0
random_uniform = random.uniform(1.0, 10.0)
print(f"Random float between 1.0 and 10.0: {random_uniform}")
# Generate a random float from a Gaussian distribution
random_gauss = random.gauss(0, 1) # mean=0, stddev=1
print(f"Random float from Gaussian distribution: {random_gauss}")
# Initialize the random number generator with a seed
random.seed(42)
# Generate a random float after setting the seed
random_float_seeded = random.random()
print(f"Random float with seed 42: {random_float_seeded}")Last updated on