Sequence selection and permutation
Choose one or more items from a collection, or reorder a mutable sequence for a simulation.
Python · Module
Python's random module supplies pseudo-random values for distributions, integer ranges, and sequence operations. Its default Mersenne Twister generator is not suitable for security-sensitive randomness.
The module offers functions for numeric distributions and sequence operations such as choosing, shuffling, and sampling. Its default generator is based on Mersenne Twister, while SystemRandom obtains values from the operating system.
import random
random.random()
random.randrange(start, stop[, step])
random.choice(seq)
random.sample(population, k, *, counts=None)
random.shuffle(x)
random.seed(a=None, version=2)| Name | Type | Description |
|---|---|---|
a | optional seed value | Seed value used to initialize the generator; the page documents seed() as a module function and supports an optional value. |
Module functions return values appropriate to their operation, such as floats, integers, selected sequence elements, or modified sequences.
import random
random.seed(42)
items = ["red", "green", "blue"]
print(random.choice(items))
print(random.sample(items, k=2))
print(random.randrange(1, 10))This seeds the default generator, selects one item, samples two distinct items, and chooses an integer from a half-open range.
Choose one or more items from a collection, or reorder a mutable sequence for a simulation.
Generate repeatable inputs for tests, demos, and simulations by initializing the generator.
Produce values from supported probability distributions for modeling and Monte Carlo workloads.
The module generates pseudo-random values, with random() producing a float in the half-open interval from 0.0 through values below 1.0. Its core generator is Mersenne Twister.
Follow-up: How would you generate security-sensitive tokens? Use the secrets module rather than this module's pseudo-random generator.
Use randrange() for an integer selected from a range, choice() for one sequence element, sample() for distinct elements without replacement, and shuffle() to mutate a sequence in place.
Follow-up: What happens if sample() requests more elements than the population contains? It raises ValueError because sampling is without replacement.
seed() initializes the generator's state, allowing repeatable pseudo-random sequences when the same supported seed is used. Reproducibility is useful for tests and simulations, but it does not make values secure.
Follow-up: How can an operating-system-backed generator be used? Instantiate SystemRandom, which uses os.urandom() as its source.
RandomSystemRandomchoicechoicesrandrangerandintsampleshuffle