Q&A
What are the Python random functions?
Overview
The random module generates pseudo-random numbers - deterministic sequences that look random, produced by an algorithm (Python uses the Mersenne Twister). It covers everything from simple coin flips to sampling and statistical distributions. The crucial caveat: it is not cryptographically secure, so anything security-sensitive (tokens, passwords, keys) must use secrets.
graph TD
A[random module] --> B[Floats: random(), uniform()]
A --> C[Integers: randint(), randrange()]
A --> D[Selection: choice, choices, sample, shuffle]
A --> E[Distributions: gauss, expovariate, ...]
A --> F[seed() for reproducibility]
A -.NOT secure.-> G[Use 'secrets' for crypto]
style G fill:#1e1b4b,color:#fff
Generating Numbers
import random
random.random() # float in [0.0, 1.0)
random.uniform(1, 10) # float in [1, 10]
random.randint(1, 6) # integer in [1, 6] inclusive (a die roll)
random.randrange(0, 10, 2) # like range(): 0,2,4,6,8 → one of these
Note randint(a, b) is inclusive of both ends, unlike range.
Selecting from Sequences
colors = ["red", "green", "blue"]
random.choice(colors) # one random element
random.choices(colors, k=2) # k elements WITH replacement (can repeat)
random.choices(colors, weights=[10, 1, 1], k=5) # weighted selection
random.sample(colors, k=2) # k UNIQUE elements WITHOUT replacement
deck = [1, 2, 3, 4, 5]
random.shuffle(deck) # shuffles IN PLACE (returns None)
Key distinction: choices samples with replacement (repeats possible), sample samples without replacement (all unique).
Statistical Distributions
random.gauss(mu=0, sigma=1) # normal (Gaussian) distribution
random.normalvariate(0, 1) # alternative normal
random.expovariate(lambd=1.5) # exponential distribution
random.triangular(0, 10, 5) # triangular distribution
Reproducibility with seed()
Seeding makes the "random" sequence repeatable - essential for testing and reproducible experiments:
random.seed(42)
print(random.randint(1, 100)) # always the same value after seed(42)
random.seed(42)
print(random.randint(1, 100)) # identical - reproducible
Same seed → same sequence. Without a seed, Python seeds from the system time/entropy.
Security: Use secrets, Not random
The random module is predictable: given enough outputs, its internal state (and future values) can be reconstructed. For tokens, passwords, session IDs, or anything security-relevant, use the secrets module:
import secrets
secrets.token_hex(16) # secure random hex token
secrets.randbelow(100) # secure random int [0, 100)
secrets.choice(["a", "b"]) # secure choice
This is the single most important point about Python randomness.
NumPy's random (for arrays / data science)
For vectorized random arrays, NumPy has its own generator:
import numpy as np
rng = np.random.default_rng(42) # modern API, seedable
rng.integers(1, 7, size=10) # array of 10 dice rolls
rng.normal(0, 1, size=(3, 3)) # 3x3 normal samples
Why This Matters in Interviews
Python interviews use this to test breadth and the security caveat. Know the common functions (random, randint inclusive, choice, shuffle in-place), the choices (with replacement) vs sample (without) distinction, seed() for reproducibility, and - most importantly - that random is not cryptographically secure so secrets is required for security contexts. Mentioning NumPy's generator for array work shows data-science awareness.
Common Pitfalls
- Using
randomfor passwords/tokens/keys instead ofsecrets(a real security flaw). - Expecting
shuffle()to return a list - it shuffles in place and returnsNone. - Confusing
choices(repeats allowed) withsample(unique). - Forgetting
randint(a, b)includesb(off-by-one vsrange). - Assuming unseeded runs are reproducible - seed explicitly for tests.
References
- Python
randommodule: https://docs.python.org/3/library/random.html - Python
secretsmodule: https://docs.python.org/3/library/secrets.html