- Courses
- 💻Programming Languages
- 🐍Python
- Standard Library Deep Dive
- Random & Secrets
On this page
Random & Secrets
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Why randomness matters
Randomness appears in many programs: simulations, games, experiments, A/B testing, password generation, API keys, and session tokens.
The key point: not all randomness is equal.
Python gives you two main tools:
random→ fast, deterministic, not securesecrets→ slower, unpredictable, secure
To write correct and safe software, you must understand:
- How each module generates values
- Why one is predictable and the other is not
- When to use each one
The random module — pseudo‑randomness
What “pseudo‑random” means
The random module uses a pseudo‑random number generator (PRNG).
A PRNG:
- Starts from an internal state called a seed
- Applies a deterministic mathematical formula
- Produces a sequence of numbers that look random
- Is fully predictable if you know the seed and the algorithm
This is ideal for:
- Simulations (e.g., Monte Carlo methods)
- Games (e.g., dice rolls, loot drops)
- Sampling (e.g., picking random rows from a dataset)
- Data shuffling (e.g., randomizing order of items)
- Non‑security‑critical randomness
It is not safe for passwords, tokens, or anything involving attackers.
Generating random numbers
Random float in ([0.0, 1.0))
import random
x = random.random()
This is the base primitive: many other operations are built on top of it.
Random integer (inclusive)
n = random.randint(1, 10) # 1 ≤ n ≤ 10
Use this when you need a whole number in a closed interval.
Random number from a range with step
n = random.randrange(0, 100, 5) # 0, 5, 10, ..., 95
This is useful when you need values aligned to a step (e.g., multiples of 5).
Random choice and sampling
Choose one element from a sequence
item = random.choice(["red", "blue", "green"])
This is like drawing one card from a deck.
Choose multiple elements with replacement
items = random.choices([1, 2, 3], k=5)
Elements can repeat, because each draw is independent.
Choose multiple elements without replacement
subset = random.sample(range(100), 10)
This is like drawing 10 unique lottery numbers from 0–99.
Sampling is fundamental in statistics, testing, and randomized algorithms.
Shuffling sequences
cards = [1, 2, 3, 4, 5]
random.shuffle(cards)
This randomly reorders the list in place.
Typical uses:
- Shuffling a deck of cards in a game
- Randomizing the order of questions in a quiz
- Randomizing dataset order before splitting into train/test sets
Seeding the random generator
A PRNG is deterministic: the same seed → the same sequence.
random.seed(42)
print(random.random())
print(random.random())
print(random.random())
If you run this code again with the same seed, you will get the exact same three values.
This is extremely useful for:
- Reproducible experiments
- Unit tests
- Debugging
But it also shows why random is not secure:
if someone can guess or control the seed, they can predict all “random” values.
The secrets module — cryptographically secure randomness
Why secrets exists
Security requires unpredictability.
Attackers must not be able to guess:
- Password reset tokens
- Session IDs
- API keys
- Security codes
The secrets module uses system‑level entropy sources, which are:
- Non‑deterministic
- Not reproducible on demand
- Designed to be hard to predict
- Suitable for cryptographic use
You should treat secrets as your default choice for anything involving security.
Secure random numbers
import secrets
n = secrets.randbelow(100) # 0 ≤ n < 100
This is the secure counterpart of random.randrange(100).
Use it when you need a random integer that an attacker must not be able to predict.
Secure random choice
token = secrets.choice(["A", "B", "C"])
This is useful when building secure tokens from a set of characters, such as:
- Uppercase letters
- Digits
- A custom alphabet for codes
Generating secure tokens
Hexadecimal token
secrets.token_hex(16) # 32 hex characters
This returns a random sequence of bytes, encoded as hexadecimal.
Good for logs, IDs, or any place where hex is convenient.
URL‑safe token
secrets.token_urlsafe(32)
This returns a random string safe to use in URLs and cookies.
Typical uses:
- Password reset links
- Session identifiers
- API tokens
- CSRF tokens
These tokens are long and unpredictable, which makes brute‑forcing them impractical.
Comparing random and secrets
Conceptual comparison
Featurerandom``secretsMain purposeSimulations, games, samplingSecurity, authenticationPredictable if seed knownYesNo (designed to be unpredictable)Cryptographically secureNoYesUse for passwords/tokensNeverAlways
A simple rule:
If an attacker could benefit from predicting your random values,
usesecrets, notrandom.
Best practices
-
Use
randomfor:- Simulations
- Games
- Non‑security data shuffling and sampling
-
Use
secretsfor:- Passwords
- API keys
- Session tokens
- Any authentication or security‑sensitive identifier
-
Do not generate passwords or tokens with
random -
Use
random.seed()only when you explicitly need reproducible results (tests, experiments) -
Prefer
secrets.token_urlsafe()for web‑visible identifiers (links, cookies, URLs) -
Avoid writing your own randomness algorithms; rely on Python’s standard library
These practices reduce the risk of predictable randomness and security vulnerabilities.
Summary
In this lesson, you learned:
- The difference between pseudo‑random (
random) and cryptographically secure (secrets) randomness - How the
randommodule works, why it is deterministic, and where it is appropriate - How the
secretsmodule uses system entropy to generate unpredictable values - How to generate numbers, shuffle data, sample sequences, and create secure tokens
- How to choose the correct module based on whether security is involved
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Datetime & Time
Next
Itertools & Functools
-
Why randomness matters
-
The
randommodule — pseudo‑randomness- What “pseudo‑random” means
- Generating random numbers
- Random choice and sampling
- Shuffling sequences
- Seeding the random generator
-
The
secretsmodule — cryptographically secure randomness- Why
secretsexists - Secure random numbers
- Secure random choice
- Generating secure tokens
- Why
-
Comparing
randomandsecrets- Conceptual comparison
-
Best practices
-
Summary
