Python random Module

The random module in Python provides tools for generating random numbers and performing random operations, such as selecting random elements from a list, generating random permutations, and more. It uses pseudo-random number generators (PRNGs) based on the Mersenne Twister algorithm.

Table of Contents

  1. Introduction
  2. Seed Functions
  3. Generating Random Numbers
    • random
    • uniform
    • randint
    • randrange
    • choice
    • choices
    • shuffle
    • sample
  4. Random Distributions
    • betavariate
    • expovariate
    • gammavariate
    • gauss
    • lognormvariate
    • normalvariate
    • vonmisesvariate
    • paretovariate
    • weibullvariate
  5. Examples
    • Basic Random Number Generation
    • Random Selection from a List
    • Shuffling a List
    • Generating Random Distributions
  6. Real-World Use Case
  7. Conclusion
  8. References

Introduction

The random module provides a suite of functions for generating random numbers and performing random operations. These functions are useful for simulations, games, randomized algorithms, and more.

Seed Functions

seed

Initializes the random number generator. If a seed value is provided, the generator will produce the same sequence of numbers each time.

import random

random.seed(10)
print(random.random())  # 0.5714025946899135

Output:

0.5714025946899135

getstate and setstate

getstate returns an object capturing the current internal state of the generator. setstate restores the state.

import random

state = random.getstate()
print(random.random())  # Generates a random number
random.setstate(state)  # Restores the state
print(random.random())  # Generates the same random number as before

Output:

0.2346378948083142
0.2346378948083142

Generating Random Numbers

random

Returns a random float number between 0.0 and 1.0.

import random

print(random.random())  # Example: 0.6370472390475487

Output:

0.6764111066791086

uniform

Returns a random float number between a and b.

import random

print(random.uniform(1, 10))  # Example: 7.065849951565783

Output:

8.591283512314774

randint

Returns a random integer between a and b (inclusive).

import random
print(random.randint(1, 10))  # Example: 3

Output:

3

randrange

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

import random
print(random.randrange(0, 10, 2))  # Example: 4

Output:

2

choice

Returns a randomly selected element from a non-empty sequence.

import random
print(random.choice(['apple', 'banana', 'cherry']))  # Example: 'banana'

Output:

apple

choices

Returns a list of k elements selected from the population with replacement.

import random
print(random.choices(['apple', 'banana', 'cherry'], k=2))  # Example: ['banana', 'apple']

Output:

['apple', 'banana']

shuffle

Shuffles the sequence in place.

import random
items = [1, 2, 3, 4, 5]
random.shuffle(items)
print(items)  # Example: [3, 5, 2, 1, 4]

Output:

[2, 4, 3, 1, 5]

sample

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

import random
print(random.sample([1, 2, 3, 4, 5], k=3))  # Example: [2, 5, 3]

Output:

[3, 1, 2]

Random Distributions

betavariate

Beta distribution.

import random
print(random.betavariate(2, 5))  # Example: 0.2707529280273536

Output:

0.18085320274247021

expovariate

Exponential distribution.

import random
print(random.expovariate(1 / 5))  # Example: 6.243506751381307

Output:

3.114680717208038

gammavariate

Gamma distribution.

import random
print(random.gammavariate(2, 2))  # Example: 5.79104864262046

Output:

6.2919114284259186

gauss

Gaussian (normal) distribution.

import random
print(random.gauss(0, 1))  # Example: -0.7373074713213723

Output:

0.22841780514487042

lognormvariate

Log normal distribution.

import random
print(random.lognormvariate(0, 1))  # Example: 0.3059596807020291

Output:

2.8062813753720266

normalvariate

Normal distribution.

import random
print(random.normalvariate(0, 1))  # Example: -0.019127211509878153

Output:

1.356484065427931

vonmisesvariate

Von Mises distribution.

import random
print(random.vonmisesvariate(0, 4))  # Example: 0.3547186937688787

Output:

0.9051804526180156

paretovariate

Pareto distribution.

import random
print(random.paretovariate(1))  # Example: 1.614141065587326

Output:

1.2107481803365356

weibullvariate

Weibull distribution.

import random
print(random.weibullvariate(1, 1.5))  # Example: 0.9850812176329475

Output:

0.24179212302471356

Examples

Basic Random Number Generation

Generate a random float, integer, and element from a list.

import random

print(random.random())  # Example: 0.6822039129653426
print(random.randint(1, 10))  # Example: 7
print(random.choice(['red', 'blue', 'green']))  # Example: 'blue'

Output:

0.28193516677200614
7
green

Random Selection from a List

Select a random element and a sample of elements from a list.

import random

items = ['apple', 'banana', 'cherry', 'date']
print(random.choice(items))  # Example: 'banana'
print(random.sample(items, k=2))  # Example: ['cherry', 'apple']

Output:

cherry
['date', 'apple']

Shuffling a List

Shuffle a list in place.

import random

items = [1, 2, 3, 4, 5]
random.shuffle(items)
print(items)  # Example: [4, 1, 5, 3, 2]

Output:

[5, 2, 3, 1, 4]

Generating Random Distributions

Generate numbers from various distributions.

import random

print(random.normalvariate(0, 1))  # Example: 0.04226714492009356
print(random.expovariate(1 / 10))  # Example: 8.362158292496075

Output:

-1.0876297531135755
6.308380041699212

Real-World Use Case

Simulating a Dice Roll

Simulate rolling a six-sided die.

import random

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

print(roll_dice())  # Example: 4

Output:

5

Password Generator

Generate a random password.

import random
import string

def generate_password(length):
    characters = string.ascii_letters + string.digits + string.punctuation
    return ''.join(random.choice(characters) for i in range(length))

print(generate_password(10))  # Example: 'aB3!dEf&gH'

Output:

SZmvy.mFl$

Conclusion

The random module in Python provides a wide range of functions for generating random numbers and performing random operations. These functions are useful for simulations, games, testing, and various other applications where randomness is needed.

References

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top