Python Standard Library · Lesson 117 of 149

Python random and secrets

What you will learn

  • random(), randint, uniform, randrange
  • choice, sample, choices, shuffle
  • What pseudo-random means, and seeds
  • Separate generators: random.Random
  • Why security needs the secrets module

1. Pseudo-random numbers

The random module produces numbers that look random. They come from a mathematical formula that starts from a seed value; the sequence only seems unpredictable. That is pseudo-random. It is perfect for games, simulations and shuffling, and not good enough for security (section 7).

import random

2. Random numbers

Call Result
random.random() a float, 0.0 up to but not including 1.0
random.uniform(a, b) a float between a and b
random.randint(a, b) an integer from a to b, both included
random.randrange(start, stop, step) like range: stop excluded
random.gauss(mu, sigma) a bell-curve (normal) value
random.seed(1)
print(random.random())
print(random.randint(1, 6))
print(random.uniform(1, 2))
print(random.randrange(0, 10, 2))
0.13436424411240122
1
1.2550690257394217
6

These exact values appeared with seed(1) on Python 3.13; the numbers could differ in another Python version. Invalid ranges raise errors:

random.randint(5, 1)
ValueError: empty range in randrange(5, 2)

(randint(a, b) calls randrange(a, b + 1), which is why the message shows 5, 2.)

Quick check: which can return 6: `randint(1, 6)` or `randrange(1, 6)`?

Only randint(1, 6). randrange(1, 6) stops before 6.

3. Seeds make runs repeatable

Starting from the same seed gives the same sequence:

random.seed(1)
print(random.random())
0.13436424411240122

That is the same first number as above. A fixed seed is useful for tests and for lessons, so that the output can be checked. Without seed, Python seeds itself from the system (for example from the operating system's randomness or the time), so each run differs.

4. Choosing from a sequence

items = ["a", "b", "c", "d", "e"]
random.seed(7)
print(random.choice(items))
print(random.sample(items, 3))
print(random.choices(items, k=4))
print(random.choices(items, weights=[10, 1, 1, 1, 1], k=6))
c
['b', 'd', 'c']
['a', 'e', 'a', 'c']
['d', 'a', 'a', 'a', 'a', 'a']
Function What it does
choice(seq) one random item
sample(seq, k) k different items (no repeats)
choices(seq, k=n) n items with repeats allowed
choices(seq, weights=[...], k=n) some items more likely than others
  • sample works on any sequence, including range (random.sample(range(100), 5) picks five different numbers from 0 to 99) and strings.
  • Asking for more than there is, or choosing from nothing, raises an error:
random.sample(items, 9)
random.choice([])
ValueError: Sample larger than population or is negative
IndexError: Cannot choose from an empty sequence

Shuffling

shuffle rearranges a list in place and returns None (lesson 7.4):

l = items[:]
random.shuffle(l)
print(l, items)
['b', 'c', 'd', 'e', 'a'] ['a', 'b', 'c', 'd', 'e']

The copy items[:] was shuffled and the original is unchanged. To get a shuffled copy in one step, use random.sample(items, len(items)). Shuffling a deck:

deck = [r + s for s in "SHDC" for r in "A23456789TJQK"]
random.seed(10)
random.shuffle(deck)
print(len(deck), deck[:5], len(set(deck)))
52 ['TH', 'QD', '2C', '9C', '4C'] 52

5. Large numbers behave as expected

Over many trials, random results even out. This check rolls a die 6,000 times:

from collections import Counter

random.seed(3)
rolls = [random.randint(1, 6) for _ in range(6000)]
print(sorted(Counter(rolls).items()))
[(1, 994), (2, 985), (3, 1063), (4, 1010), (5, 981), (6, 967)]

Each face appears about 1,000 times, but not exactly. Randomness gives approximate shares, never a perfect split. A famous use is the Monte Carlo method: estimating π by throwing random points at a square and counting those inside a circle:

random.seed(5)
n = 100000
inside = sum(1 for _ in range(n) if random.random() ** 2 + random.random() ** 2 <= 1)
print(4 * inside / n)
3.14024

6. Your own generator

Calling random.seed(...) changes the one shared generator for the whole program, which can surprise other code. A better habit: create your own generator object with random.Random(seed). It has the same methods and does not disturb anything else:

rng = random.Random(42)
print(rng.randint(1, 100), rng.randint(1, 100))

rng2 = random.Random(42)
print(rng2.randint(1, 100))
82 15
82

Two generators with the same seed give the same sequence, independently. This is the clean way to make a simulation or a test repeatable.

7. secrets: when it matters

The pseudo-random generator is predictable to someone who sees enough of its output. For anything security-related, use the secrets module, which draws from the operating system's secure source of randomness:

Need Use
password, token, key, reset link, session id secrets
game, simulation, shuffling a playlist random
import secrets
import string

print(len(secrets.token_hex(16)))
print(secrets.randbelow(10) < 10)
print(secrets.choice("abc") in "abc")
print(type(secrets.token_bytes(4)))
32
True
True
<class 'bytes'>
  • token_hex(16) gives 16 random bytes as 32 hexadecimal characters; token_urlsafe(n) gives text safe to put in a web address; token_bytes(n) gives raw bytes.
  • randbelow(n) is a secure random integer from 0 to n - 1.
  • secrets.compare_digest(a, b) compares secrets in a way that does not leak information through timing (True for equal strings, False otherwise).
  • There is no seed: secure randomness cannot be repeated, by design.

A password generator picks each character with secrets.choice:

alphabet = string.ascii_letters + string.digits
pw = "".join(secrets.choice(alphabet) for _ in range(12))
print(len(pw), all(c in alphabet for c in pw))
12 True

The string module supplies ready-made character sets: ascii_lowercase, ascii_uppercase, ascii_letters, digits, punctuation.

Worked example: a password, a raffle and a fair game

A password generator that guarantees each kind of character, a raffle that can be repeated (to prove the draw was fair) and a simple dice game using its own generator.

import random
import secrets
import string


def make_password(length=12):
    symbols = "!#$%&*?"
    alphabet = string.ascii_letters + string.digits + symbols
    while True:
        pw = "".join(secrets.choice(alphabet) for _ in range(length))
        if (any(c.islower() for c in pw) and any(c.isupper() for c in pw)
                and any(c.isdigit() for c in pw) and any(c in symbols for c in pw)):
            return pw


pw = make_password()
print(len(pw), any(c.isdigit() for c in pw))


def draw_winners(entries, n, seed=None):
    rng = random.Random(seed)
    return rng.sample(entries, n)


people = ["Rina", "Sam", "Lee", "Amy", "Joe", "Kim"]
print(draw_winners(people, 2, seed=2026))
print(draw_winners(people, 2, seed=2026))

rng = random.Random(8)


def play(rounds):
    score = 0
    for _ in range(rounds):
        a, b = rng.randint(1, 6), rng.randint(1, 6)
        score += 1 if a > b else -1 if a < b else 0
    return score


print([play(10) for _ in range(5)])

loaded = random.Random(4).choices(["heads", "tails"], weights=[7, 3], k=1000)
print(loaded.count("heads"), loaded.count("tails"))
12 True
['Rina', 'Lee']
['Rina', 'Lee']
[-2, -1, -6, -3, 0]
675 325
Part Idea
make_password uses secrets unpredictable; the while loop retries until all four kinds of character appear
draw_winners(..., seed=2026) the same seed gives the same winners, so a draw can be re-checked
random.Random(8) the dice game has its own generator, leaving the global one alone
choices(..., weights=[7, 3]) about 70 percent heads: here 675 of 1,000, not exactly 700

The names are made up, and the password itself is not printed because it changes on every run. For a real raffle you would not want a seed that anyone can guess before the draw.

Common mistakes

  • Using random for passwords or tokens.
  • Expecting randint(1, 6) to exclude 6 (it includes both ends).
  • Expecting shuffle to return the list (it returns None and changes the list).
  • Using choices when you need no repeats (use sample).
  • Calling random.seed in library code, which disturbs everyone's randomness.
  • Assuming a fixed seed gives the same numbers on every Python version.
  • Expecting an exact split from random trials.

Key takeaways

  • random produces pseudo-random numbers: random(), randint(a, b) (inclusive), uniform, randrange (stop excluded).
  • choice, sample (no repeats), choices (repeats, weights) and shuffle (in place) work on sequences.
  • A seed makes the sequence repeatable; use random.Random(seed) for your own independent generator.
  • For passwords, tokens and keys use secrets, which cannot be seeded or predicted.
  • Random results are approximate over many trials, never exact.

Practice

1. How do you simulate rolling two dice and adding them?

Show answer

random.randint(1, 6) + random.randint(1, 6)

2. Which function picks 3 different names from a list?

Show answer

random.sample(names, 3)

3. What does random.shuffle(lst) return?

Show answer

None. It rearranges lst in place.

4. Why is random unsuitable for generating a password?

Show answer

Its sequence is predictable from the generator's state, so an attacker could work out other values. Use secrets.

5. How can you make a simulation repeatable without affecting other code?

Show answer

Create rng = random.Random(seed) and call rng.randint(...) and so on, instead of seeding the global generator.

6. What is the difference between choice and choices?

Show answer

choice returns one item; choices(seq, k=n) returns a list of n items with repeats allowed, and supports weights.