Python Reference ยท Standard Library: Math, Data and Text
The random module
Reference for Python's random module: pick random numbers and items, shuffle and sample lists, seed for repeatable results, and when to use secrets instead.
The random module generates pseudo-random numbers: values that look random but come from a deterministic algorithm (the Mersenne Twister). It can pick random numbers in a range, choose items from a sequence, shuffle a list and draw from common probability distributions.
Because the sequence is determined by an internal state, you can make it repeatable by calling random.seed() with a fixed value. That is ideal for simulations, games and tests, and unsuitable for passwords, tokens or anything security related; use the secrets module for those.
import random print(random.randint(1, 6))
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Frequently used names
| Name | Description |
|---|---|
seed(a=None) |
Initializes the generator. With no argument it uses system randomness (the default at startup). |
random() |
Float in [0.0, 1.0). |
uniform(a, b) |
Float between a and b. |
randint(a, b) |
Integer N with a <= N <= b (both ends included). |
randrange(stop), randrange(start, stop[, step]) |
Like range(): the stop value is excluded. |
choice(seq) |
One random element of a non-empty sequence. |
choices(population, weights=None, k=1) |
k elements chosen with replacement, optionally weighted. Returns a list. |
sample(population, k) |
k unique elements chosen without replacement. Returns a list. |
shuffle(x) |
Reorders a mutable sequence in place. Returns None. |
gauss(mu, sigma), normalvariate, triangular, expovariate, betavariate, binomialvariate (3.12+) |
Random values from probability distributions. |
getrandbits(k), randbytes(n) |
Random integer with k bits; n random bytes (3.9+). Not secure. |
getstate(), setstate(state) |
Save and restore the generator's state. |
Random(seed), SystemRandom() |
Independent generator objects; SystemRandom uses the operating system's secure source. |
Usage notes
- Not cryptographically secure. An attacker who sees enough output can predict later values. Use
secrets(orrandom.SystemRandom) for tokens, passwords and keys. - Seeds give repeatability on the same Python version. The exact values produced by
choice,shuffleandsampleare not guaranteed to stay the same across Python releases, so do not store seeded outputs as expected values in long-lived tests; test properties (length, membership) instead. randintincludes both ends,randrangeexcludes the stop. Mixing them up gives off-by-one bugs.shufflechanges the list and returnsNone.x = random.shuffle(x)setsxtoNone. Userandom.sample(x, k=len(x))for a shuffled copy.choiceneeds a sequence with an index. It fails on sets and dictionaries; convert withlist()orsorted()first.sample()needs a sequence too (sets were removed in 3.11).- Empty input fails.
choice([])raisesIndexError;samplewithklarger than the population raisesValueError. - Weighted choice. Use
choices(items, weights=..., k=n); weights are relative and need not add up to 1. Unlikesample, results can repeat. - Threads. The module-level functions share one hidden generator that is safe to call from several threads. For independent, reproducible streams (for example one per worker), create separate
Randomobjects. - Fork and processes. A copied process starts with the same generator state, so reseed in each worker if they must differ.
Related
secrets,statistics,math,itertools- Lessons: Math and random, Lists, Project: number guessing