HomepythonThe random module in Python

The random module in Python

The random module in Python provides tools for generating random numbers and performing random operations. It includes functions for generating random integers, floats, and sequences, as well as utilities for random sampling, shuffling, and more. This guide will cover the essentials of the random module, including its functions and practical applications.

Overview of the random Module

The random module includes functionality for:

  • Generating random numbers
  • Random sampling
  • Shuffling data
  • Working with distributions

Importing the Module

Before using the random module, you need to import it:

import random

Generating Random Numbers

random.random()

Returns a random float in the range [0.0, 1.0).

import random

print(random.random())  # Output: A random float between 0.0 and 1.0

random.uniform(a, b)

Returns a random float in the range [a, b].

import random

print(random.uniform(1.5, 10.5))  # Output: A random float between 1.5 and 10.5

random.randint(a, b)

Returns a random integer in the inclusive range [a, b].

import random

print(random.randint(1, 10))  # Output: A random integer between 1 and 10 (inclusive)

random.randrange(start, stop[, step])

Returns a randomly selected element from range(start, stop, step).

import random

print(random.randrange(0, 100, 5))  # Output: A random element from the range 0 to 100 with step 5

random.choice(seq)

Returns a random element from the non-empty sequence seq.

import random

print(random.choice(['apple', 'banana', 'cherry']))  # Output: A random element from the list

random.choices(population, weights=None, *, cum_weights=None, k=1)

Returns a list of k elements chosen from the population with optional weights or cum_weights.

import random

print(random.choices(['apple', 'banana', 'cherry'], weights=[10, 1, 1], k=5))
# Output: A list of 5 elements chosen from the list, with 'apple' more likely to be chosen

Random Sampling and Shuffling

random.sample(population, k)

Returns a list of k unique elements chosen from the population sequence.

import random

print(random.sample(range(100), 5))  # Output: A list of 5 unique elements chosen from the range 0 to 99

random.shuffle(x[, random])

Shuffles the sequence x in place.

import random

data = [1, 2, 3, 4, 5]
random.shuffle(data)
print(data)  # Output: The list shuffled in place

Working with Distributions

The random module provides functions to generate random numbers from various probability distributions.

random.gauss(mu, sigma)

Returns a random float from a Gaussian distribution with mean mu and standard deviation sigma.

import random

print(random.gauss(0, 1))  # Output: A random float from a Gaussian distribution with mean 0 and stddev 1

random.expovariate(lambd)

Returns a random float from an exponential distribution with rate lambd.

import random

print(random.expovariate(1.5))  # Output: A random float from an exponential distribution with rate 1.5

random.betavariate(alpha, beta)

Returns a random float from a Beta distribution with parameters alpha and beta.

import random

print(random.betavariate(2.5, 1.5))  # Output: A random float from a Beta distribution

random.gammavariate(alpha, beta)

Returns a random float from a Gamma distribution with shape alpha and scale beta.

import random

print(random.gammavariate(2, 1))  # Output: A random float from a Gamma distribution

random.lognormvariate(mu, sigma)

Returns a random float from a log-normal distribution with mean mu and standard deviation sigma.

import random

print(random.lognormvariate(0, 1))  # Output: A random float from a log-normal distribution

Seeding the Random Number Generator

random.seed(a=None, version=2)

Initializes the random number generator. If a is omitted or None, the current system time is used. If a is an int, it is used as the seed.

import random

random.seed(42)
print(random.random())  # Output: A reproducible random float due to the fixed seed

Practical Examples

Example 1: Simulating Dice Rolls

Using random.randint() to simulate rolling a six-sided die.

import random

def roll_dice():
    return random.randint(1, 6)

print(roll_dice())  # Output: A random integer between 1 and 6

Example 2: Generating a Random Password

Using random.choices() to generate a random password from a set of characters.

import random
import string

def generate_password(length):
    characters = string.ascii_letters + string.digits + string.punctuation
    return ''.join(random.choices(characters, k=length))

print(generate_password(12))  # Output: A random 12-character password

Example 3: Randomly Shuffling a Deck of Cards

Using random.shuffle() to shuffle a deck of cards.

import random

def create_deck():
    suits = 'hearts diamonds clubs spades'.split()
    ranks = '2 3 4 5 6 7 8 9 10 J Q K A'.split()
    return [f"{rank} of {suit}" for suit in suits for rank in ranks]

deck = create_deck()
random.shuffle(deck)
print(deck)  # Output: The deck shuffled in place

The random module in Python provides a comprehensive suite of tools for generating random numbers and performing random operations. Whether you need to generate random integers, floats, or sequences, or work with different probability distributions, the random module has the necessary functions.

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular