random
The random module implements pseudo-random number generators for various distributions. It is useful for simulations, games, security (with caveats), and statistical sampling. Python uses the Mersenne Twister as the core generator.
Quick Reference
| Function | Description |
|---|---|
random() | Random float in [0.0, 1.0) |
randint(a, b) | Random integer from a to b (inclusive) |
randrange(start, stop, step) | Random integer from range |
choice(seq) | Random element from sequence |
shuffle(x) | Shuffle list in place |
sample(population, k) | Sample k unique elements |
seed(a, version) | Initialize generator |
uniform(a, b) | Random float in [a, b] |
triangular(low, high, mode) | Triangular distribution |
Seeding the Generator
Set the seed for reproducible results.
import random
random.seed(42)
print(random.random())
# 0.6394267984578837
# Same seed = same sequence
random.seed(42)
print(random.random())
# 0.6394267984578837
Without seeding, Python seeds from the operating system entropy source.
Basic Random Numbers
random()
Returns a random float in the range [0.0, 1.0).
import random
for _ in range(5):
print(random.random())
# 0.13334722086717508
# 0.8471536681046147
# 0.3708787306102069
# 0.7296064703100954
# 0.60140939580676593
randint(a, b)
Returns a random integer N where a <= N <= b. Both endpoints are inclusive.
import random
# Roll a six-sided die
die_roll = random.randint(1, 6)
print(die_roll)
# 4
# Generate a random password digit
digit = random.randint(0, 9)
print(digit)
# 7
randrange(start, stop, step)
Like range(), returns a random integer from the sequence. Does not include the stop value.
import random
# Random even number from 0 to 100
even = random.randrange(0, 101, 2)
print(even)
# 42
# Random month (1-12)
month = random.randrange(1, 13)
print(month)
# 8
Selecting from Sequences
choice(seq)
Returns a single random element from a non-empty sequence.
import random
colors = ["red", "green", "blue", "yellow"]
print(random.choice(colors))
# green
# Pick a random letter
import string
letter = random.choice(string.ascii_uppercase)
print(letter)
# M
sample(population, k)
Returns a list of k unique elements from population without replacement.
import random
# Deal 5 cards from a deck
deck = list(range(1, 53))
hand = random.sample(deck, 5)
print(hand)
# [17, 42, 8, 23, 51]
# Sample without replacement
items = ["a", "b", "c", "d", "e"]
selection = random.sample(items, 3)
print(selection)
# ['c', 'a', 'e']
shuffle(x)
Shuffles a list in place. Returns None.
import random
cards = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
random.shuffle(cards)
print(cards)
# ['Q', '3', 'K', '5', 'J', '9', '7', '2', '8', '6', 'A', '4', '10']
# Fisher-Yates shuffle - works on any sequence
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)
# [3, 1, 5, 2, 4]
Floating-Point Distributions
uniform(a, b)
Returns a random float N where a <= N <= b.
import random
# Random temperature between 20 and 25 Celsius
temp = random.uniform(20, 25)
print(f"Temperature: {temp:.1f}C")
# Temperature: 22.7C
# Random delay between 0.5 and 2.0 seconds
delay = random.uniform(0.5, 2.0)
print(f"Delay: {delay:.3f}s")
# Delay: 1.234s
triangular(low, high, mode)
Returns a random float from a triangular distribution. The mode argument defaults to the midpoint.
import random
# Simulate wait times with known average
for _ in range(5):
wait = random.triangular(5, 15, 10) # min=5, max=15, mode=10
print(f"Wait time: {wait:.1f} minutes")
# Wait time: 9.2 minutes
# Wait time: 7.8 minutes
# Wait time: 11.4 minutes
# Wait time: 10.1 minutes
# Wait time: 6.5 minutes
Common Patterns
Random password generation
import random
import string
def generate_password(length=16):
chars = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(chars) for _ in range(length))
print(generate_password())
# kR9#mP2$vL5@nQ8
Random item with weights
import random
# Weighted selection using random.choices
items = ["common", "rare", "epic", "legendary"]
weights = [70, 20, 8, 2]
for _ in range(10):
loot = random.choices(items, weights=weights, k=1)[0]
print(loot)
# common
# common
# rare
# common
# common
# common
# epic
# common
# common
# legendary
Shuffling a string
import random
def shuffle_string(s):
chars = list(s)
random.shuffle(chars)
return ''.join(chars)
print(shuffle_string("hello"))
# lohel
Security Considerations
The Mersenne Twister is not cryptographically secure. For security-sensitive randomness (passwords, tokens, keys), use the secrets module instead:
import secrets
# Generate a secure random token
token = secrets.token_urlsafe(32)
print(token[:20] + "...")
# q8XKLm2pMzN5Rv...
# Secure random integer in range
secure_num = secrets.randbelow(1000000)
print(secure_num)
# 847293