How can I generate random integers between 0 and 9 (inclusive) in Python?
For example, 0
, 1
, 2
, 3
, 4
While many posts demonstrate how to get one random integer, the original question asks how to generate random integers (plural):
How can I generate random integers between 0 and 9 (inclusive) in Python?
For clarity, here we demonstrate how to get multiple random integers.
Given
>>> import random
lo = 0
hi = 10
size = 5
Code
Multiple, Random Integers
# A
>>> [lo + int(random.random() * (hi - lo)) for _ in range(size)]
[5, 6, 1, 3, 0]
# B
>>> [random.randint(lo, hi) for _ in range(size)]
[9, 7, 0, 7, 3]
# C
>>> [random.randrange(lo, hi) for _ in range(size)]
[8, 3, 6, 8, 7]
# D
>>> lst = list(range(lo, hi))
>>> random.shuffle(lst)
>>> [lst[i] for i in range(size)]
[6, 8, 2, 5, 1]
# E
>>> [random.choice(range(lo, hi)) for _ in range(size)]
[2, 1, 6, 9, 5]
Sample of Random Integers
# F
>>> random.choices(range(lo, hi), k=size)
[3, 2, 0, 8, 2]
# G
>>> random.sample(range(lo, hi), k=size)
[4, 5, 1, 2, 3]
Details
Some posts demonstrate how to natively generate multiple random integers.1 Here are some options that address the implied question:
[0.0, 1.0)
N
such that a <= N <= b
randint(a, b+1)
k
selections from a population (with replacement, Python 3.6+)k
unique selections from a population (without replacement):2See also R. Hettinger's talk on Chunking and Aliasing using examples from the random
module.
Here is a comparison of some random functions in the Standard Library and Numpy:
| | random | numpy.random |
|-|-----------------------|----------------------------------|
|A| random() | random() |
|B| randint(low, high) | randint(low, high) |
|C| randrange(low, high) | randint(low, high) |
|D| shuffle(seq) | shuffle(seq) |
|E| choice(seq) | choice(seq) |
|F| choices(seq, k) | choice(seq, size) |
|G| sample(seq, k) | choice(seq, size, replace=False) |
You can also quickly convert one of many distributions in Numpy to a sample of random integers.3
Examples
>>> np.random.normal(loc=5, scale=10, size=size).astype(int)
array([17, 10, 3, 1, 16])
>>> np.random.poisson(lam=1, size=size).astype(int)
array([1, 3, 0, 2, 0])
>>> np.random.lognormal(mean=0.0, sigma=1.0, size=size).astype(int)
array([1, 3, 1, 5, 1])
1Namely @John Lawrence Aspden, @S T Mohammed, @SiddTheKid, @user14372, @zangw, et al. 2@prashanth mentions this module showing one integer. 3Demonstrated by @Siddharth Satpathy