Python Random Module: randint, choice, seed and More
The Python random module generates random numbers, picks, samples and shuffles with no install. Learn the functions you will actually use, how seed makes results repeatable, how weights work, and why passwords and tokens need the secrets module instead, with tested output.
- The Python random module is built in:
import randomand you are ready. randint(a, b)includes both ends;randrange(a, b)excludesb.random.seed(42)makes the sequence repeatable, which is ideal for tests and demos.choicespicks with replacement,samplepicks without.shufflechanges the list in place and returnsNone.- Never use
randomfor passwords or tokens. Use thesecretsmodule.
Dice games, quiz apps, A/B test buckets, sample datasets, retry jitter: they all need randomness. The Python random module covers these jobs with a small set of functions, but a few details trip people up. Is the upper bound included? Why did shuffle return None? Why are my numbers the same on every run? And when is random not safe at all?
Every example below was run on Python 3.13.6. Where a seed is set, you will get exactly the same output on your machine, because the generator is deterministic. If you are just starting, our Python tutorial for beginners covers imports and lists first.
What is the Python random module?
random is a standard library module that produces pseudo-random numbers. They look random and pass statistical tests, but they come from a formula: the Mersenne Twister algorithm. Given the same starting state, called the seed, it produces the same sequence every time. That is a feature for simulations and tests, and a weakness for anything security related.
All the module-level functions share one hidden generator. When you call random.randint() and then random.choice(), both draw from the same stream, so the order of calls changes the results.
Random integers: randint and randrange
import random
random.seed(42)
print(random.random()) # 0.6394267984578837
print([random.randint(1, 6) for _ in range(5)]) # [1, 6, 3, 2, 2]
print([random.randrange(0, 10, 2) for _ in range(5)]) # [2, 0, 8, 0, 8]
The difference matters:
randint(1, 6)returns 1 to 6 inclusive, perfect for a dice roll.randrange(start, stop, step)followsrange()rules, sostopis excluded.randrange(0, 10, 2)returns only even numbers from 0 to 8.
If you want a random index into a list of length n, randrange(n) is the natural fit, because it can never return n itself and cause an IndexError.
Random floats: random and uniform
random.random() returns a float in the half-open range [0.0, 1.0). For any other range, use uniform:
print(round(random.uniform(1.5, 2.5), 4)) # 1.9219
A common pattern is a probability check, such as if random.random() < 0.1: to run something about 10 percent of the time. Another is retry jitter: time.sleep(base * random.uniform(0.5, 1.5)) spreads retries so that many clients do not hit a recovering server at the same instant.
Picking items: choice and choices
colors = ["red", "green", "blue"]
print(random.choice(colors)) # red
print(random.choices(colors, k=5)) # ['red', 'red', 'green', 'green', 'blue']
choice returns one item. choices returns a list of k items with replacement, so the same item can appear more than once, as red and green did above. Calling choice on an empty list raises IndexError, so guard against empty input.
sample vs choices: with or without replacement
print(random.sample(range(1, 11), 3)) # [9, 7, 4]
random.sample(colors, 5)
# ValueError: Sample larger than population or is negative
sample picks unique positions, like drawing raffle tickets from a hat without putting them back. That is why asking for 5 items from a 3-item list fails, while choices(colors, k=5) works fine. Use sample for lottery numbers, picking winners or selecting test accounts; use choices for simulating repeated independent events.
| Function | Returns | Repeats possible? |
|---|---|---|
choice(seq) |
One item | n/a |
choices(seq, k=n) |
List of n | Yes |
sample(seq, n) |
List of n | No |
shuffle(list) |
None (in place) |
No |
Shuffling a list
deck = list(range(1, 11))
random.shuffle(deck)
print(deck) # [9, 10, 6, 3, 4, 2, 7, 1, 5, 8]
print(random.shuffle(deck)) # None
shuffle rearranges the list itself and returns None. Writing deck = random.shuffle(deck) is a classic bug that leaves you with None. If you need a shuffled copy and want to keep the original, use random.sample(deck, len(deck)). Shuffle only works on mutable sequences, so convert a tuple or string to a list first.
random.seed: repeatable results
random.seed(42); a = [random.randint(1, 100) for _ in range(3)]
random.seed(42); b = [random.randint(1, 100) for _ in range(3)]
print(a, b, a == b) # [82, 15, 4] [82, 15, 4] True
Setting a seed resets the generator to a known state, so the following calls repeat exactly. Use it in unit tests, data science notebooks, games with shareable level codes and any demo where readers should see your output. Without a seed, Python seeds itself from the operating system, so each run differs.
Tip: seed once at the start of a program or test, not before every call. Reseeding inside a loop with the same value returns the same number over and over.
Weighted random choices
Pass weights to make some outcomes more likely. We drew 100,000 times with a 90 to 10 weighting:
import collections
random.seed(7)
picks = random.choices(["common", "rare"], weights=[90, 10], k=100_000)
print(collections.Counter(picks))
# {'common': 90095, 'rare': 9905}
The result landed within 0.1 percent of the target. Weights do not need to sum to 100; [9, 1] gives the same odds. This is how you would build loot tables, traffic splits for an experiment or realistic fake data where most orders are small and a few are large. collections.Counter is covered in our Python collections guide.
Is Python random actually fair?
We rolled a virtual die 60,000 times with randint(1, 6). A fair die should land on each face about 10,000 times:
| Face | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| Count | 9,986 | 10,061 | 9,954 | 9,987 | 10,002 | 10,010 |
Every face is within 0.7 percent of 10,000, exactly the kind of small wobble you expect from real randomness. The Mersenne Twister has excellent statistical quality for games, simulations and sampling. Its weakness is predictability, not bias.
Other distributions: gauss and friends
Not all randomness is uniform. Heights, response times and measurement errors cluster around an average. random.gauss(mu, sigma) draws from a normal distribution:
import statistics
random.seed(1)
g = [random.gauss(170, 10) for _ in range(50_000)]
print(round(statistics.mean(g), 2), round(statistics.stdev(g), 2))
# 170.05 10.01
The sample mean and standard deviation came out almost exactly at the 170 and 10 we asked for. The module also offers expovariate for waiting times, triangular, betavariate and more, which are handy when you need realistic test data generation.
Independent generators with random.Random
Because module functions share one global state, a library that calls random can shift your sequence. Create your own generator object to isolate it:
r1 = random.Random(99)
r2 = random.Random(99)
print(r1.randint(1, 1000), r2.randint(1, 1000)) # 414 414
Each Random instance keeps its own state, so two instances with the same seed produce the same values no matter what other code does. This is the cleanest way to make a simulation reproducible inside a larger program.
random vs secrets: security matters
Because Mersenne Twister is deterministic, anyone who knows or recovers the state can predict future values. We showed this with a seeded “password”:
random.seed(3); pw1 = "".join(random.choice("abc123") for _ in range(8))
random.seed(3); pw2 = "".join(random.choice("abc123") for _ in range(8))
print(pw1 == pw2) # True
For passwords, API keys, reset links and session tokens, use secrets, which draws from the operating system’s cryptographic source:
import secrets
print(len(secrets.token_hex(8))) # 16 (8 random bytes as hex)
print(secrets.randbelow(10)) # 0 to 9, unpredictable
random.SystemRandom uses the same OS source. We seeded one twice with the same value and got different numbers each time, confirming that its seed has no effect.
How fast is random?
| Call | Time per call |
|---|---|
random.random() |
26.9 ns |
random.randint(1, 6) |
336.8 ns |
secrets.randbelow(6) |
575.3 ns |
Best of three runs of 200,000 calls each. randint is about 12 times slower than random() because of argument checks and rejection sampling, but even a million calls take only a third of a second. secrets is slower again, yet still far too fast to matter for generating a token.
Using random in tests
- Seed the generator in a pytest fixture so failures can be reproduced.
- Print or log the seed when a randomized test fails, so you can rerun the exact case.
- Pass a
random.Randominstance into your code instead of calling the module directly; tests can then inject a seeded one. - For deeper randomized testing, try property-based testing, which generates and shrinks inputs for you.
Python random cheat sheet
| Need | Use |
|---|---|
| Float 0 to 1 | random.random() |
| Integer a to b inclusive | random.randint(a, b) |
| Random index | random.randrange(len(seq)) |
| One item | random.choice(seq) |
| Unique items | random.sample(seq, k) |
| Weighted picks | random.choices(seq, weights=w, k=n) |
| Shuffle in place | random.shuffle(lst) |
| Repeatable run | random.seed(42) |
| Token or password | secrets.token_urlsafe() |
Final thoughts
The Python random module is small but covers almost every everyday need: integers, floats, picks, samples, shuffles and weighted draws. Remember that randint includes both ends, that shuffle returns None, and that a seed makes results repeatable. Keep random for games, simulations and tests, and switch to secrets the moment security is involved.
Frequently asked questions
Is randint inclusive in Python?
Yes. random.randint(a, b) can return both a and b. If you want the upper bound excluded, use random.randrange(a, b) instead.
How do I get the same random numbers every time?
Call random.seed with a fixed value, such as random.seed(42), before generating numbers. The same seed always produces the same sequence on the same Python version.
Why does random.shuffle return None?
shuffle changes the list in place and returns None by design. Shuffle the list on its own line, or use random.sample(items, len(items)) to get a shuffled copy.
What is the difference between choice and choices?
choice returns a single item. choices returns a list of k items picked with replacement and accepts weights, so the same item can appear more than once.
Is Python random safe for passwords?
No. The random module is predictable once its state is known. Use the secrets module, for example secrets.token_urlsafe or secrets.choice, for passwords, tokens and keys.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.