To use random in Python, add import random and call a function from the module: random.random() for a float from 0.0 up to but not including 1.0, random.randint(1, 6) for an integer where both ends can appear, or random.choice(items) to pick one element. The module is for simulations, games and sampling, not for passwords or tokens.
The examples below were written against the Python 3 documentation for the random module. Any output shown is example output, because the whole point of the module is that the numbers change from run to run.
Random numbers: random(), randint(), randrange() and uniform()
import random
print(random.random()) # float, 0.0 <= X < 1.0
print(random.randint(1, 6)) # int, 1 <= N <= 6
print(random.randrange(0, 10, 2)) # one of 0, 2, 4, 6, 8
print(random.uniform(1.5, 4.5)) # float between 1.5 and 4.5
Example output:
0.7364712141640124
4
6
2.9183620417
The four functions differ in what they return and in how they treat the upper end:
| Function | Returns | Upper end included? |
|---|---|---|
random() | float, 0.0 <= X < 1.0 | No (1.0 never appears) |
randint(a, b) | int, a <= N <= b | Yes |
randrange(start, stop, step) | int from range(start, stop, step) | No |
uniform(a, b) | float between a and b | Maybe, depending on floating-point rounding |
The off-by-one difference between randint(1, 6) and randrange(1, 6) catches many people. The docs define randint(a, b) as an alias for randrange(a, b+1), so a six-sided die is randint(1, 6) but randrange(1, 7).
The docs also advise against keyword arguments with randrange(), because randrange(start=100) is interpreted as randrange(0, 100, 1). Pass the arguments by position. Since Python 3.12, passing a non-integer such as randrange(10.0) raises TypeError.
How to pick a random item from a list
import random
colors = ["red", "green", "blue", "yellow"]
print(random.choice(colors))
Example output:
blue
choice() needs a non-empty sequence. On an empty list it raises IndexError, so check the list before you call it if the list can be empty. It works on lists, tuples and strings, but not on sets or dictionaries, because they cannot be indexed by position. For those, convert first: random.choice(list(my_set)).
How to pick several random items: sample() and choices()
Two functions return a list of several picks, and the difference is whether an item can be picked twice.
import random
names = ["Ana", "Ben", "Chen", "Dara", "Eli"]
print(random.sample(names, k=3)) # no repeats
print(random.choices(names, k=3)) # repeats possible
Example output:
['Dara', 'Ana', 'Eli']
['Ben', 'Ben', 'Chen']
sample() selects without replacement and leaves the original list unchanged. If k is larger than the population, it raises ValueError. choices() selects with replacement, so it can return the same element more than once and k can be any size.
Since Python 3.11, the population given to sample() must be a sequence. Passing a set raises an error instead of being converted automatically.
Weighted random choices
choices() accepts relative weights:
import random
outcomes = ["common", "rare", "legendary"]
weights = [80, 18, 2]
print(random.choices(outcomes, weights=weights, k=5))
Example output:
['common', 'common', 'rare', 'common', 'common']
Weights are relative, so they do not have to add up to 100. You can pass cum_weights (cumulative weights) instead, but not both: giving both raises TypeError. Weights must be non-negative and finite, and since Python 3.9 a ValueError is raised if all of them are zero.
To sample from a population with known counts, sample() takes a keyword-only counts argument (added in Python 3.9). The docs show that sample(['red', 'blue'], counts=[4, 2], k=5) behaves like sampling from ['red']*4 + ['blue']*2.
How to shuffle a list in Python
import random
deck = [1, 2, 3, 4, 5]
random.shuffle(deck)
print(deck)
Example output:
[3, 5, 1, 4, 2]
shuffle() reorders the list in place and returns None. A common bug is writing deck = random.shuffle(deck), which replaces your list with None. It also cannot shuffle immutable sequences such as tuples or strings. The docs give the workaround: random.sample(x, k=len(x)) returns a new shuffled list and leaves the original alone.
If you only need a few random elements rather than a full reordering, sample() is the simpler call. For building lists with other logic, see Python list comprehension, which pairs well with the functions above, for example [random.randint(1, 6) for _ in range(5)] to roll five dice.
How to get the same random numbers every time: seed()
The generator behind the module is a pseudo-random one: the docs say Python uses the Mersenne Twister, which produces 53-bit precision floats and has a period of 2**19937-1. Given the same starting state, it produces the same sequence. random.seed() sets that starting state.
import random
random.seed(42)
first = [random.randint(1, 100) for _ in range(3)]
random.seed(42)
second = [random.randint(1, 100) for _ in range(3)]
print(first == second)
Output:
True
If you call seed() with no argument, or with None, the docs say the current system time is used. Since Python 3.11 the seed must be None, an int, float, str, bytes or bytearray. Earlier versions accepted any hashable object.
Seeding is useful for tests and for reproducing a simulation. The docs warn that most of the module's algorithms and seeding functions can change between Python versions. Only the random() method is promised to keep producing the same sequence from the same seed, so do not store seeded results and expect another Python version to reproduce your other calls.
Independent generators with random.Random
The functions on the module share one global generator. If two parts of a program need separate, reproducible streams, create separate instances:
import random
rng_a = random.Random(1)
rng_b = random.Random(2)
print(rng_a.randint(1, 10), rng_b.randint(1, 10))
Each Random object has its own state and exposes the same methods as the module, so seeding one does not disturb the other. The docs state that the global generator and Random instances are thread-safe, with one documented exception: gauss() can return the same value to two threads that call it at the same moment. Use normalvariate(), a lock, or one instance per thread if that matters.
Random numbers from a distribution
For simulations, the module has distribution functions as well. The common ones:
random.gauss(mu, sigma)andrandom.normalvariate(mu, sigma)draw from a normal distribution. The defaults of 0.0 and 1.0 exist since Python 3.11.random.triangular(low, high, mode)draws betweenlowandhigh, clustered aroundmode.random.expovariate(lambd)draws from an exponential distribution, wherelambdis 1.0 divided by the desired mean.random.binomialvariate(n, p)counts successes inntrials with success probabilityp. It was added in Python 3.12, so older versions raiseAttributeError.
Is Python's random secure?
No. The Mersenne Twister is, in the docs' words, completely unsuitable for cryptographic purposes, and the module's generators should not be used for security purposes. For passwords, session tokens, reset links and API keys, use the secrets module, which draws from the operating system's secure source:
import secrets
print(secrets.token_hex(16))
print(secrets.choice("abcdefghijkmnopqrstuvwxyz23456789"))
Example output:
9f2c4e7a1b8d03c65a7e4d2f90b1c8e3
q
The same warning applies to random.randbytes() (added in Python 3.9): the docs say not to use it for security tokens and to use secrets.token_bytes() instead. The JavaScript version of this split is covered in Math.random() vs crypto.getRandomValues().
Common mistakes
- Expecting
randint(1, 6)to stop at 5. It includes 6. - Reseeding inside a loop. Calling
random.seed(42)before every call returns the same value every time. Seed once, at program start. - Using
choice()on an empty list. It raisesIndexError. - Using
randomfor anything security related. Switch tosecrets.
Frequently asked questions
- Is randint() inclusive of the upper number?
- Yes. random.randint(a, b) returns N with a <= N <= b, so both ends can appear. It is an alias for randrange(a, b+1). randrange(a, b), like range(a, b), excludes b.
- How do I get the same random numbers every time in Python?
- Call random.seed() with a fixed value, such as random.seed(42), before generating numbers. The same seed gives the same sequence from the same Python version. The docs say seeding algorithms can change across versions, so do not rely on identical output between versions.
- What is the difference between random.choice() and random.sample()?
- choice() returns one element. sample(population, k) returns a new list of k unique positions from the population, chosen without replacement, so no position is picked twice. If k is larger than the population, sample() raises ValueError.
- Can I use the random module for passwords or tokens?
- No. The Python docs say the module's generators should not be used for security purposes and point to the secrets module instead. Use secrets.token_hex(), secrets.token_urlsafe() or secrets.choice() for anything an attacker must not guess.
- Why does random.sample() fail on a set?
- Since Python 3.11 the population must be a sequence, and automatic conversion of sets to lists was removed. Convert it yourself with random.sample(list(my_set), k) or sorted(my_set).