Random Module in Python
Random Module in Python
The random module in Python is part of the standard library and provides a suite of functions for generating random numbers, selecting random elements, and performing other random operations. It can be used for simulations, generating random data for testing, and other scenarios where randomness is needed.
Commonly Used Functions in the random Module
random.random()Returns a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive).
import randomprint(random.random()) # Output: A random float between 0 and 1random.randint(a, b)Returns a random integer such that (both endpoints are inclusive).
import randomprint(random.randint(1, 10)) # Output: Random integer between 1 and 10 (inclusive)random.uniform(a, b)Returns a random floating-point number between and (inclusive of and exclusive of ).
import randomprint(random.uniform(1.5, 10.5)) # Output: A random float between 1.5 and 10.5random.choice(sequence)Returns a randomly selected element from a non-empty sequence (like a list, tuple, or string).
import randomfruits = ['apple', 'banana', 'cherry', 'date']print(random.choice(fruits)) # Output: A random fruit from the listrandom.shuffle(sequence)Randomly shuffles the elements of a sequence (list in most cases) in place. This modifies the original list.
import randomnumbers = [1, 2, 3, 4, 5]random.shuffle(numbers)print(numbers) # Output: Shuffled list, e.g., [4, 1, 5, 2, 3]random.sample(sequence, k)Returns a list of
kunique elements chosen from the sequence. It does not modify the original sequence.
import randomnumbers = [1, 2, 3, 4, 5, 6]print(random.sample(numbers, 3)) # Output: A random sample of 3 numbers from the listrandom.choices(sequence, weights=None, cum_weights=None, k=1)Returns a list of
kelements chosen from the sequence, with the possibility of choosing elements with weighted probabilities. Theweightsorcum_weightsargument can be used to specify the likelihood of each element being chosen.
import randomfruits = ['apple', 'banana', 'cherry']weights = [0.5, 0.3, 0.2] # apple has the highest chance of being selectedprint(random.choices(fruits, weights=weights, k=3)) # Output: List of 3 random fruits based on weightsrandom.seed(a=None)Initializes the random number generator. Providing a specific seed value ensures reproducibility. The same seed will generate the same sequence of random numbers every time.
import randomrandom.seed(42) # Seed the random number generatorprint(random.randint(1, 100)) # Output: Always the same random number for the same seedrandom.gauss(mu, sigma)Returns a random number drawn from a Gaussian (normal) distribution with mean
muand standard deviationsigma.
import randomprint(random.gauss(0, 1)) # Output: A random number from a normal distribution (mean=0, stddev=1)random.triangular(low, high, mode)Returns a random number from a triangular distribution, with the specified
low,high, andmodevalues.
import randomprint(random.triangular(1, 10, 5)) # Output: A random number with a triangular distribution
Example Usage:
import random# 1. Generate a random float between 0 and 1print("Random float between 0 and 1:", random.random())# 2. Generate a random integer between 1 and 100print("Random integer between 1 and 100:", random.randint(1, 100))# 3. Select a random element from a listfruits = ['apple', 'banana', 'cherry', 'date']print("Random fruit:", random.choice(fruits))# 4. Shuffle a list of numbersnumbers = [1, 2, 3, 4, 5]random.shuffle(numbers)print("Shuffled numbers:", numbers)# 5. Generate a sample of 3 random elementssample = random.sample(fruits, 3)print("Random sample of 3 fruits:", sample)# 6. Generate a weighted random choiceweights = [0.5, 0.3, 0.2]chosen_fruit = random.choices(fruits, weights=weights, k=1)print("Weighted random fruit:", chosen_fruit)# 7. Generate a random number using a Gaussian distributionprint("Random number from Gaussian distribution:", random.gauss(0, 1))Output Example:
Random float between 0 and 1: 0.3745401188473625Random integer between 1 and 100: 39Random fruit: cherryShuffled numbers: [4, 1, 5, 3, 2]Random sample of 3 fruits: ['banana', 'apple', 'cherry']Weighted random fruit: ['apple']Random number from Gaussian distribution: 0.744436780845363Conclusion
The random module is very useful for generating random numbers and performing random operations in Python. It provides a variety of methods to handle different types of randomness, from basic random numbers to weighted choices, Gaussian distributions, and even shuffling sequences. You can use the module for simulations, testing, and generating random data for your applications.