How to Generate Random Integers in Python

Use random.randint(a, b) for a random integer between a and b inclusive, random.randrange(start, stop) when you want the stop value excluded or need a step, secrets.randbelow(n) for anything security-sensitive, and NumPy's default_rng().integers() when you need many integers at once.
The examples were run on Python 3.13 and NumPy 2.5. Outputs shown for seeded code are reproducible on the same versions; outputs from secrets will differ on every run.
random.randint and random.randrange
Both live in the standard random module and use the Mersenne Twister generator.
import random
random.seed(42)
rolls = [random.randint(1, 6) for _ in range(10)]
print(rolls)
print(random.randrange(10)) # 0..9
print(random.randrange(0, 100, 5)) # 0, 5, 10, ..., 95
print(random.randrange(-5, 6)) # -5..5
[6, 1, 1, 6, 3, 2, 2, 2, 6, 1]
8
10
4
| Call | Range of results | Notes |
|---|---|---|
randint(a, b) | a to b, both included | Exactly randrange(a, b + 1) |
randrange(stop) | 0 to stop - 1 | Same semantics as range() |
randrange(start, stop, step) | Elements of range(start, stop, step) | Handy for even numbers, multiples, etc. |
The inclusive upper bound of randint is the single most common source of off-by-one bugs, because almost everything else in Python (slices, range, NumPy) excludes the end. If you think in range() terms, use randrange consistently.
Since Python 3.12, randrange raises TypeError for non-integer arguments such as 10.0; convert with int() first.
Picking from a collection: choice, sample, choices
When the integers you want are not a contiguous range, or you want several at once, pick from a sequence:
import random
random.seed(1)
ports = [8000, 8080, 8443, 9000]
print(random.choice(ports)) # one element
print(random.sample(range(1, 50), k=6)) # 6 distinct values
print(random.choices(range(1, 7), k=8)) # 8 values, repeats allowed
8080
[37, 5, 17, 8, 32, 29]
[3, 3, 2, 3, 6, 3, 4, 5]
choice(seq)returns one element.sample(population, k)returnskdistinct elements (sampling without replacement).choices(population, weights=None, k=1)samples with replacement and supports weights, e.g.choices([0, 1], weights=[9, 1], k=10).
Secure random integers with secrets
The random module is deterministic: anyone who observes enough outputs can reconstruct the generator state and predict future values. For tokens, PINs, password-reset codes, or anything an attacker might want to guess, use secrets, which draws from the operating system's cryptographically secure source.
import secrets
pin = secrets.randbelow(10**6) # 0..999999
print(f"{pin:06d}")
die = secrets.randbelow(6) + 1 # 1..6
print(die)
print(secrets.choice(range(100, 200)))
print(secrets.token_hex(8))
122628
2
163
da780286f9348048
(Your output will differ; that is the point.) secrets.randbelow(n) returns 0 <= x < n. For a range [a, b], use a + secrets.randbelow(b - a + 1). secrets cannot be seeded, so it is unsuitable for reproducible simulations. random.SystemRandom() offers the same OS source with the full random API (randint, sample, ...).
NumPy: default_rng().integers
For arrays of random integers, NumPy is dramatically faster. Use the Generator API returned by np.random.default_rng():
import numpy as np
rng = np.random.default_rng(seed=42)
print(rng.integers(1, 7, size=10)) # high is exclusive: 1..6
print(rng.integers(1, 6, size=10, endpoint=True)) # high inclusive: 1..6
print(rng.integers(0, 100, size=(2, 3))) # 2x3 array
print(rng.integers(0, 256, size=4, dtype=np.uint8))
print(type(rng.integers(5, 10)))
[1 5 4 3 3 6 1 5 2 1]
[4 6 5 5 5 5 4 1 6 3]
[[50 37 18]
[92 78 64]]
[182 160 4 103]
<class 'numpy.int64'>
Endpoint semantics
rng.integers(low, high) excludes high by default, like range. Pass endpoint=True to include it, which matches random.randint. With a single argument, rng.integers(10) means 0..9. A scalar call returns a NumPy integer (numpy.int64), not a Python int; call int() on it if you need to serialize it to JSON.
The legacy functions np.random.randint and np.random.seed still work but use a global RandomState. NumPy recommends default_rng for new code: it uses the better PCG64 generator and keeps state in an object you pass around rather than in hidden global state.
Seeding and reproducibility
Seeding makes a pseudo-random sequence repeatable, which is what you want in tests, simulations and data-science experiments. Prefer a dedicated generator instance over the module-level functions so that other code calling random cannot shift your sequence:
import random
a = random.Random(2026)
b = random.Random(2026)
print([a.randint(1, 100) for _ in range(5)])
print([b.randint(1, 100) for _ in range(5)])
random.seed(2026)
state = random.getstate()
first = [random.randint(1, 100) for _ in range(3)]
random.setstate(state)
again = [random.randint(1, 100) for _ in range(3)]
print(first == again)
[16, 41, 65, 66, 83]
[16, 41, 65, 66, 83]
True
A few caveats:
- Python guarantees the same sequence for the same seed across versions only for
random()itself; methods likerandrangeandsamplehave changed their algorithms in the past. Pin your Python version if bit-for-bit reproducibility matters. - Since Python 3.11,
random.seed()accepts onlyNone,int,float,str,bytesandbytearray. - Seeding
randomdoes not seed NumPy, and vice versa. Seed each generator you use.
Unique random integers
To draw integers without repeats, do not loop and reject duplicates; sample without replacement:
import random
import numpy as np
random.seed(3)
print(random.sample(range(1, 1_000_001), k=5)) # range is not materialised
rng = np.random.default_rng(3)
print(rng.choice(1_000_000, size=5, replace=False))
print(rng.permutation(10))
try:
random.sample(range(10), k=11)
except ValueError as e:
print("ValueError:", e)
[249524, 621430, 570666, 136759, 387927]
[179440 811501 85648 236810 181364]
[9 4 8 5 1 6 2 3 7 0]
ValueError: Sample larger than population or is negative
random.sample accepts a range directly and does not build the list in memory, so sampling a few values out of millions is cheap. To shuffle every value in a range, use random.shuffle(list(range(n))) or rng.permutation(n).
Performance
Timing one million integers in the range 1 to 100 (best of five runs, timeit, Python 3.13, NumPy 2.5 on the build container for this article; treat the numbers as indicative only):
| Method | Time for 1,000,000 values |
|---|---|
[random.randint(1, 100) for ...] | 230 ms |
[random.randrange(1, 101) for ...] | 187 ms |
random.choices(range(1, 101), k=N) | 56 ms |
[secrets.randbelow(100) + 1 for ...] | 828 ms |
rng.integers(1, 101, size=N) | 2.5 ms |
randint is a thin wrapper over randrange, which explains the small gap. NumPy is roughly two orders of magnitude faster because it fills the array in compiled code. secrets is the slowest, but for the handful of values a token or PIN needs, its cost is negligible.
Common pitfalls
- Mixing up inclusive and exclusive bounds.
random.randint(1, 6)can return 6;np.random.default_rng().integers(1, 6)cannot. - Using
randomfor security. Session IDs, OTPs and reset tokens needsecrets. - Re-seeding inside a loop. Calling
random.seed(42)before every draw returns the same number every time. - Seeding with the time in tests. It defeats reproducibility; use a fixed integer and log it.
- Sharing a NumPy generator across processes. Each worker gets an identical copy; create independent streams with
rng.spawn(n)ornp.random.SeedSequence(...).spawn(n).
Summary
For a single integer, random.randint(a, b) (inclusive) or random.randrange(start, stop) (exclusive). For distinct values, random.sample. For anything an attacker might guess, secrets.randbelow. For large arrays, np.random.default_rng(seed).integers(low, high, size=...), remembering that high is excluded unless you pass endpoint=True. Seed a dedicated generator instance when you need reproducible results.
PythonFactorial in Python
Compute factorials in Python with a loop, recursion, math.factorial, reduce and memoization, with input validation, big integers and real timeit benchmarks.
PythonTwo-dimensional arrays
Create 2D arrays in Python with nested list comprehensions or NumPy, avoid the [[0]*n]*m aliasing bug, and index, iterate, transpose and slice correctly.
DataKurtosis in Python
Compute kurtosis in Python with scipy.stats.kurtosis, pandas Series.kurt and NumPy. Excess vs Pearson, the bias flag, worked examples and how to interpret it.