Python random module
last modified November 18, 2026 Python 3.15
In this article we show how to generate pseudo-random numbers in Python with
the random module.
Random number generators
A random number generator (RNG) produces a sequence of values that does not show any recognizable pattern. Random number generators fall into two categories: hardware random number generators and pseudo-random number generators. Hardware generators derive values from physical processes and are believed to produce genuinely random numbers. Pseudo-random number generators (PRNG) compute the values with an algorithm. The values look random, but they are deterministic: the same starting state always produces the same sequence.
In computing, random numbers are used in games, simulations, sampling, testing, and cryptography.
The random module
The random module implements pseudo-random number generators
for various distributions. It uses the Mersenne Twister algorithm, which
is fast and has a very long period of 219937−1, but it is
predictable once enough of its output is known. It must not be used for
security; the secrets module is meant for that.
The module-level functions share one hidden instance of the
random.Random class. The examples in this article produce
different values on every run unless a seed is set.
Random floats
The random.random function returns a float in the half-open
interval [0.0, 1.0). Most other functions of the module are built on top
of it.
import random
for _ in range(4):
print(random.random())
The example prints four random floats.
$ python rand_float.py 0.6548755328066571 0.6748880350815799 0.555936999198507 0.98309167698541
The seed
The seed is the value that initializes the generator. The same
seed always produces the same sequence of numbers, which is useful for
reproducible simulations and tests. The seed is set with the
random.seed function. When it is not set, or is called without
an argument, Python seeds the generator from the operating system's
randomness source (or the current time if that is unavailable).
import random
random.seed(16)
first = [random.random() for _ in range(3)]
random.seed(16)
second = [random.random() for _ in range(3)]
print(first)
print(second)
print(first == second)
random.seed('falcon')
print(random.randint(1, 100), random.randint(1, 100))
We seed the generator twice with the same value and generate three numbers each time.
random.seed('falcon')
The seed can also be a string, bytes, or a bytearray; it is
converted to an integer. Since Python 3.11, the seed must be
None, an integer, a float, a string, bytes, or a
bytearray.
$ python same_seed.py [0.36152277491407514, 0.480480665601294, 0.4169526266056648] [0.36152277491407514, 0.480480665601294, 0.4169526266056648] True 28 1
Random integers
The random.randint(a, b) function returns an integer from the
closed interval [a, b]; both ends are included. The
random.randrange function takes the same arguments as
range, so the stop value is excluded and a step can be
given.
import random print([random.randint(1, 10) for _ in range(10)]) print([random.randrange(1, 10) for _ in range(10)]) print([random.randrange(0, 101, 10) for _ in range(10)]) print([random.randrange(6) for _ in range(10)])
We generate four lists of ten random integers.
print([random.randint(1, 10) for _ in range(10)]) print([random.randrange(1, 10) for _ in range(10)])
The first list can contain 10, the second cannot.
print([random.randrange(0, 101, 10) for _ in range(10)])
With a step of 10, only multiples of ten from 0 to 100 are returned.
$ python rand_int.py [9, 7, 6, 7, 2, 9, 8, 10, 5, 10] [1, 6, 6, 6, 9, 8, 4, 4, 7, 6] [20, 60, 80, 70, 50, 80, 100, 0, 10, 90] [5, 3, 2, 0, 3, 0, 4, 2, 5, 2]
Rolling dice
A uniform generator returns each value with the same probability. We can check this by rolling a die many times and counting the results.
import random
from collections import Counter
rolls = [random.randint(1, 6) for _ in range(6000)]
counts = Counter(rolls)
for face in range(1, 7):
print(face, counts[face])
We roll a die 6000 times and count the faces with a Counter.
Each face comes up roughly a thousand times.
$ python dice.py 1 989 2 993 3 1023 4 969 5 1003 6 1023
Random floats in a range
The random.uniform(a, b) function returns a float between
a and b. The random.triangular
function returns a float between two bounds with values near the given mode
being the most likely.
import random print([round(random.uniform(1, 10), 3) for _ in range(5)]) print([round(random.uniform(-0.5, 0.5), 3) for _ in range(5)]) print([round(random.triangular(0, 10, 8), 3) for _ in range(5)])
We round the values to three decimal places to keep the output short.
print([round(random.uniform(-0.5, 0.5), 3) for _ in range(5)])
The bounds can be negative.
print([round(random.triangular(0, 10, 8), 3) for _ in range(5)])
The values lie between 0 and 10 and cluster around 8.
$ python floats.py [1.476, 5.111, 7.655, 4.267, 8.867] [0.169, -0.328, 0.167, -0.412, -0.006] [8.068, 6.114, 3.839, 4.795, 6.4]
Choosing a random element
The random.choice function returns a random element from a
non-empty sequence.
import random
words = ['sky', 'storm', 'rock', 'falcon', 'forest']
for _ in range(4):
print(random.choice(words))
print(random.choice('abcdef'))
try:
random.choice([])
except IndexError as e:
print('error:', e)
We pick a random word four times and a random character from a string.
random.choice([])
Choosing from an empty sequence raises IndexError.
$ python rand_choice.py falcon falcon falcon sky a error: Cannot choose from an empty sequence
Weighted choices
The random.choices function picks k elements with
replacement, so an element can be picked more than once. The optional
weights or cum_weights (cumulative weights) set
the probability of each element.
import random from collections import Counter colours = ['red', 'green', 'blue'] print(random.choices(colours, k=6)) picks = random.choices(colours, weights=[70, 20, 10], k=1000) print(Counter(picks).most_common()) picks = random.choices(colours, cum_weights=[70, 90, 100], k=1000) print(Counter(picks).most_common())
We pick colours with equal and with unequal probabilities.
picks = random.choices(colours, weights=[70, 20, 10], k=1000)
Red is picked about 70 % of the time, green about 20 %, and blue about 10 %. The weights do not have to add up to 100.
picks = random.choices(colours, cum_weights=[70, 90, 100], k=1000)
Cumulative weights 70, 90, and 100 describe the same distribution and save the function from computing them.
$ python rand_choices.py
['red', 'blue', 'red', 'blue', 'red', 'red']
[('red', 676), ('green', 222), ('blue', 102)]
[('red', 689), ('green', 198), ('blue', 113)]
Shuffling
The random.shuffle function shuffles a mutable sequence in
place and returns None.
import random
words = ['sky', 'storm', 'rock', 'falcon', 'forest']
res = random.shuffle(words)
print(words, res)
random.shuffle(words)
print(words)
word = 'falcon'
letters = random.sample(word, k=len(word))
print(''.join(letters), word)
We shuffle a list of words twice.
letters = random.sample(word, k=len(word))
Strings and tuples are immutable and cannot be shuffled in place. A
sample of the full length returns a new shuffled list and
leaves the original untouched.
$ python shuffling.py ['rock', 'sky', 'falcon', 'forest', 'storm'] None ['storm', 'sky', 'falcon', 'forest', 'rock'] fcanlo falcon
Random samples
The random.sample function returns a list of k
unique elements chosen from a population, that is, sampling without
replacement.
import random
words = ['sky', 'storm', 'rock', 'falcon', 'forest']
print(random.sample(words, 3))
print(random.sample(range(1, 50), k=6))
print(random.sample(['red', 'blue'], counts=[4, 2], k=5))
try:
random.sample(words, 10)
except ValueError as e:
print('error:', e)
We draw samples from a list and a range.
print(random.sample(range(1, 50), k=6))
A lottery draw: six different numbers from 1 to 49. Sampling from a
range is efficient even for huge ranges.
print(random.sample(['red', 'blue'], counts=[4, 2], k=5))
The counts parameter repeats the elements: the population is
four red and two blue items.
$ python sampling.py ['rock', 'sky', 'forest'] [4, 23, 45, 12, 6, 49] ['blue', 'red', 'red', 'red', 'blue'] error: Sample larger than population or is negative
Random bits and bytes
The random.getrandbits function returns a non-negative
integer with the given number of random bits and
random.randbytes returns random bytes.
import random
n = random.getrandbits(16)
print(n, f'{n:016b}')
data = random.randbytes(8)
print(data.hex(), len(data))
We print a 16-bit integer in decimal and binary form and eight random bytes as hexadecimal digits.
These bytes are not suitable for keys or tokens; use
secrets.token_bytes for that.
$ python bits_bytes.py 61985 1111001000100001 051cb4f6d707aaa9 8
Distributions
Besides uniform values, the module generates numbers from common
distributions: gauss and normalvariate (normal),
expovariate (exponential), binomialvariate
(binomial, added in Python 3.12), and others.
import random
import statistics
heights = [random.gauss(175, 8) for _ in range(10_000)]
print(f'gauss: mean {statistics.mean(heights):.1f}, stdev {statistics.stdev(heights):.1f}')
waits = [random.expovariate(1 / 5) for _ in range(10_000)]
print(f'expovariate: mean {statistics.mean(waits):.2f}')
heads = [random.binomialvariate(10, 0.5) for _ in range(10_000)]
print(f'binomialvariate: mean {statistics.mean(heads):.2f}')
for k in range(11):
share = heads.count(k) / len(heads)
print(f'{k:2} {"*" * round(share * 100)}')
We generate ten thousand values from three distributions and check their
means with the statistics module.
heights = [random.gauss(175, 8) for _ in range(10_000)]
Normally distributed heights with a mean of 175 and a standard deviation of 8.
waits = [random.expovariate(1 / 5) for _ in range(10_000)]
The argument of expovariate is the rate, the reciprocal of the
mean, so the mean waiting time is about 5.
heads = [random.binomialvariate(10, 0.5) for _ in range(10_000)]
The number of heads in ten coin tosses. The text histogram shows the typical bell shape.
$ python distributions.py gauss: mean 175.1, stdev 8.0 expovariate: mean 5.02 binomialvariate: mean 5.00 0 1 * 2 ***** 3 ************ 4 ******************** 5 ************************* 6 ******************** 7 ************ 8 **** 9 * 10
Independent generators
Creating instances of random.Random gives independent
generators with their own state. Libraries and tests should use their own
instance instead of seeding the shared global generator.
import random gen1 = random.Random(42) gen2 = random.Random(42) print(gen1.randint(1, 100), gen1.randint(1, 100)) print(gen2.randint(1, 100), gen2.randint(1, 100)) random.seed(42) print(random.randint(1, 100), random.randint(1, 100))
Two generators with the same seed produce the same numbers. They also match the module-level functions seeded with the same value, because all use the same algorithm.
$ python instances.py 82 15 82 15 82 15
Saving and restoring the state
The random.getstate function returns the internal state of the
generator; random.setstate restores it. This lets us replay a
sequence from any point, not only from the seed.
import random random.seed(7) random.random() state = random.getstate() print([random.randint(1, 9) for _ in range(5)]) random.setstate(state) print([random.randint(1, 9) for _ in range(5)])
We save the state after one call, generate five numbers, restore the state, and generate the same five numbers again.
$ python state.py [3, 7, 1, 2, 9] [3, 7, 1, 2, 9]
SystemRandom
The random.SystemRandom class has the same methods as
Random but takes its values from the operating system's
randomness source (os.urandom). Its sequences cannot be
reproduced.
import random
sr = random.SystemRandom()
print(sr.randint(1, 100))
print(sr.choice(['rock', 'paper', 'scissors']))
print(sr.random())
try:
sr.seed(10)
sr.getstate()
except NotImplementedError as e:
print('error:', e)
We use the familiar methods on a SystemRandom instance.
sr.seed(10) sr.getstate()
The seed method is accepted but does nothing. The
getstate and setstate methods raise
NotImplementedError.
$ python system_random.py 87 rock 0.6710065658994122 error: System entropy source does not have state.
Monte Carlo simulation
Monte Carlo methods use random sampling to estimate numerical results. We estimate π by generating random points in a unit square and counting those that fall inside the quarter circle.
import random
rng = random.Random(1)
for n in [100, 10_000, 1_000_000]:
inside = 0
for _ in range(n):
x, y = rng.random(), rng.random()
if x * x + y * y <= 1:
inside += 1
print(f'{n:>9}: {4 * inside / n:.5f}')
The ratio of points inside the quarter circle approaches π/4. The
estimate gets better with more points. We use a seeded
Random instance, so the output is the same on every run.
$ python monte_carlo.py
100: 3.20000
10000: 3.13960
1000000: 3.14118
Command-line interface
Since Python 3.13, the module can be run from the command line. Without
options, it chooses a random word from several arguments, prints a random
integer between 1 and N for an integer argument, and a random float between
0 and N for a float argument. The -c, -i, and
-f options select the mode explicitly.
We run the module in all modes.
$ python -m random sky storm rock falcon storm $ python -m random 6 4 $ python -m random 2.5 2.3244612595825305 $ python -m random -i 100 18 $ python -m random -c heads tails tails
The secrets module
The secrets module generates cryptographically strong random
numbers suitable for passwords, account authentication, and security
tokens.
import secrets import string print(secrets.token_hex(12)) print(secrets.token_urlsafe(12)) alphabet = string.ascii_letters + string.digits password = ''.join(secrets.choice(alphabet) for _ in range(12)) print(password) print(secrets.randbelow(100))
The token_hex function returns a random hexadecimal string;
12 is the number of bytes, so the string has 24 characters. The
token_urlsafe function returns a random Base64 URL-safe string.
alphabet = string.ascii_letters + string.digits password = ''.join(secrets.choice(alphabet) for _ in range(12))
We generate a twelve-character alphanumeric password. The
secrets.randbelow function returns an integer from 0 up to,
but not including, the given value.
$ python strong.py 9d2ee9465e401ec9947ea965 G_5f6A7CXnYwe4Lr QhcJgWgKD63l 27
Source
random – Generate pseudo-random numbers
secrets – Generate secure random numbers for managing secrets
In this article we have generated pseudo-random numbers with the Python
random module. See also
Python secrets,
Python uuid, and
Python Faker.
Author
List all Python tutorials.