1891

How can I generate random integers between 0 and 9 (inclusive) in Python?

For example, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

2
  • this one is also userful: stackoverflow.com/questions/20936993/… >>> from random import SystemRandom >>> cryptogen = SystemRandom() >>> [cryptogen.randrange(3) for i in range(20)] Commented Nov 12, 2022 at 2:15
  • 1
    this works: import random; print(random.randint(0, 9)) Commented Nov 12, 2022 at 2:15

23 Answers 23

2604

Try random.randrange:

from random import randrange
print(randrange(10))
4
  • 2
    In particular, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography. Commented Dec 1, 2020 at 23:07
  • 14
    To save anyone having to navigate to the secrets module to accomplish this: import secrets secrets.randbelow(10)
    – sazerac
    Commented Feb 5, 2021 at 4:47
  • 3
    Note that the secrets module was first added to Python in version 3.6 Commented Apr 30, 2021 at 8:56
  • 2
    @user3540325: Pre-3.6, a close approximation is creating an instance of random.SystemRandom() and calling the methods of that instance; random.SystemRandom(), like secrets (which I believe is implemented in terms of it) relies on OS-supplied cryptographic randomness (e.g. CryptGenRandom on Windows, /dev/urandom on UNIX-likes). Commented May 17, 2022 at 15:25
807

Try random.randint:

import random
print(random.randint(0, 9))

Docs state:

random.randint(a, b)

Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

0
188

Try this:

from random import randrange, uniform

# randrange gives you an integral value
irand = randrange(0, 10)

# uniform gives you a floating-point value
frand = uniform(0, 10)
0
105
from random import randint

x = [randint(0, 9) for p in range(0, 10)]

This generates 10 pseudorandom integers in range 0 to 9 inclusive.

1
  • I wanted only 10 rows (RANDOM_LIMIT) on trial run of 2,500 rows (row_count) so I used random_row_nos = [randint(1, row_count) for p in range(0, RANDOM_LIMIT)] based on this answer and it worked the first time! Commented Oct 24, 2021 at 21:46
96

The secrets module is new in Python 3.6. This is better than the random module for cryptography or security uses.

To randomly print an integer in the inclusive range 0-9:

from secrets import randbelow
print(randbelow(10))

For details, see PEP 506.

Note that it really depends on the use case. With the random module you can set a random seed, useful for pseudorandom but reproducible results, and this is not possible with the secrets module.

random module is also faster (tested on Python 3.9):

>>> timeit.timeit("random.randrange(10)", setup="import random")
0.4920286529999771
>>> timeit.timeit("secrets.randbelow(10)", setup="import secrets")
2.0670733770000425
1
  • 3
    This would improve the answer and should be added. The more security minded answers should always be added if available.
    – SudoKid
    Commented Feb 7, 2018 at 17:15
75

I would try one of the following:

1.> numpy.random.randint

import numpy as np
X1 = np.random.randint(low=0, high=10, size=(15,))

print (X1)
>>> array([3, 0, 9, 0, 5, 7, 6, 9, 6, 7, 9, 6, 6, 9, 8])

2.> numpy.random.uniform

import numpy as np
X2 = np.random.uniform(low=0, high=10, size=(15,)).astype(int)

print (X2)
>>> array([8, 3, 6, 9, 1, 0, 3, 6, 3, 3, 1, 2, 4, 0, 4])

3.> numpy.random.choice

import numpy as np
X3 = np.random.choice(a=10, size=15 )

print (X3)
>>> array([1, 4, 0, 2, 5, 2, 7, 5, 0, 0, 8, 4, 4, 0, 9])

4.> random.randrange

from random import randrange
X4 = [randrange(10) for i in range(15)]

print (X4)
>>> [2, 1, 4, 1, 2, 8, 8, 6, 4, 1, 0, 5, 8, 3, 5]

5.> random.randint

from random import randint
X5 = [randint(0, 9) for i in range(0, 15)]

print (X5)
>>> [6, 2, 6, 9, 5, 3, 2, 3, 3, 4, 4, 7, 4, 9, 6]

Speed:

np.random.uniform and np.random.randint are much faster (~10 times faster) than np.random.choice, random.randrange, random.randint .

%timeit np.random.randint(low=0, high=10, size=(15,))
>> 1.64 µs ± 7.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit np.random.uniform(low=0, high=10, size=(15,)).astype(int)
>> 2.15 µs ± 38.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.random.choice(a=10, size=15 )
>> 21 µs ± 629 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit [randrange(10) for i in range(15)]
>> 12.9 µs ± 60.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit [randint(0, 9) for i in range(0, 15)]
>> 20 µs ± 386 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Notes:

1.> np.random.randint generates random integers over the half-open interval [low, high).

2.> np.random.uniform generates uniformly distributed numbers over the half-open interval [low, high).

3.> np.random.choice generates a random sample over the half-open interval [low, high) as if the argument a was np.arange(n).

4.> random.randrange(stop) generates a random number from range(start, stop, step).

5.> random.randint(a, b) returns a random integer N such that a <= N <= b.

6.> astype(int) casts the numpy array to int data type.

7.> I have chosen size = (15,). This will give you a numpy array of length = 15.

4
  • 1
    ModuleNotFoundError: No module named 'numpy'
    – SL5net
    Commented Jan 10, 2021 at 21:28
  • 1
    If that error occurs, have you installed numpy (pip install numpy) and have you imported it using import numpy as np? Commented May 8, 2021 at 13:59
  • random is a built-in module, why import it through numpy? Does numpy expand it?
    – LightCC
    Commented Apr 27, 2022 at 18:58
  • @LightCC I suppose it's faster to generate multiple random numbers because it's in C and heavily optimized. Although getting a single number would probably be faster without all that overhead (try it and see, but don't go crazy with tiny optimizations)
    – Eric Jin
    Commented Jul 30, 2022 at 1:42
36

Choose the size of the array (in this example, I have chosen the size to be 20). And then, use the following:

import numpy as np   
np.random.randint(10, size=(1, 20))

You can expect to see an output of the following form (different random integers will be returned each time you run it; hence you can expect the integers in the output array to differ from the example given below).

array([[1, 6, 1, 2, 8, 6, 3, 3, 2, 5, 6, 5, 0, 9, 5, 6, 4, 5, 9, 3]])
1
  • 3
    It's also helpful to know how Numpy can generate a random array of specified size, not just a single random number. (Docs: numpy.random.randint)
    – jkdev
    Commented Jun 25, 2017 at 18:19
33

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:

See 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

30

You need the random python module which is part of your standard library. Use the code...

from random import randint

num1= randint(0,9)

This will set the variable num1 to a random number between 0 and 9 inclusive.

1
  • 1
    You can also choose randrange(10). Commented Jul 15, 2021 at 13:03
26

Try this through random.shuffle

>>> import random
>>> nums = range(10)
>>> random.shuffle(nums)
>>> nums
[6, 3, 5, 4, 0, 1, 2, 9, 8, 7]
2
  • 3
    This is not a correct answer, and should be deleted. Commented Dec 1, 2019 at 21:01
  • @NicolasGervais This might not be the correct answer to the original question, but it is a useful answer nevertheless and so it deserve to stay right where it is.
    – user1336619
    Commented Apr 11, 2022 at 12:45
18

In case of continuous numbers randint or randrange are probably the best choices but if you have several distinct values in a sequence (i.e. a list) you could also use choice:

>>> import random
>>> values = list(range(10))
>>> random.choice(values)
5

choice also works for one item from a not-continuous sample:

>>> values = [1, 2, 3, 5, 7, 10]
>>> random.choice(values)
7

If you need it "cryptographically strong" there's also a secrets.choice in python 3.6 and newer:

>>> import secrets
>>> values = list(range(10))
>>> secrets.choice(values)
2
2
  • What if we want more numbers from the sequence? Commented Oct 3, 2017 at 13:43
  • If they should be without replacement: random.sample. With replacement you could use a comprehension with choice: for example for a list containing 3 random values with replacement: [choice(values) for _ in range(3)]
    – MSeifert
    Commented Oct 3, 2017 at 13:53
14

if you want to use numpy then use the following:

import numpy as np
print(np.random.randint(0,10))
2
  • 1
    You could tell something about "numpy".
    – Simón
    Commented Jan 20, 2017 at 4:09
  • 12
    Yeah. Thanks for the link. But I intended to mean that you could have improved your answer by providing details before just quoting two lines of code; like for what reason would someone prefer to use it instead of something already built in. Not that you're obliged to, anyway.
    – Simón
    Commented Jan 20, 2017 at 16:00
9
>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1

To get a list of ten samples:

>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]
8

You can try importing the random module from Python and then making it choose a choice between the nine numbers. It's really basic.

import random
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    

You can try putting the value the computer chose in a variable if you're going to use it later, but if not, the print function should work as such:

choice = random.choice(numbers)
print(choice)
7

Generating random integers between 0 and 9.

import numpy
X = numpy.random.randint(0, 10, size=10)
print(X)

Output:

[4 8 0 4 9 6 9 9 0 7]
0
6

Best way is to use import Random function

import random
print(random.sample(range(10), 10))

or without any library import:

n={} 
for i in range(10):
    n[i]=i

for p in range(10):
    print(n.popitem()[1])

here the popitems removes and returns an arbitrary value from the dictionary n.

5

random.sample is another that can be used

import random
n = 1 # specify the no. of numbers
num = random.sample(range(10),  n)
num[0] # is the required number
3

This is more of a mathematical approach but it works 100% of the time:

Let's say you want to use random.random() function to generate a number between a and b. To achieve this, just do the following:

num = (b-a)*random.random() + a;

Of course, you can generate more numbers.

1
  • This generates a float value. To get pure integers: num = int(round((b-a)*random.random(),1)) + a Commented Mar 16, 2021 at 19:45
3

From the documentation page for the random module:

Warning: The pseudo-random generators of this module should not be used for security purposes. Use os.urandom() or SystemRandom if you require a cryptographically secure pseudo-random number generator.

random.SystemRandom, which was introduced in Python 2.4, is considered cryptographically secure. It is still available in Python 3.7.1 which is current at time of writing.

>>> import string
>>> string.digits
'0123456789'
>>> import random
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'1'
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'5'

Instead of string.digits, range could be used per some of the other answers along perhaps with a comprehension. Mix and match according to your needs.

1
2

I thought I'd add to these answers with quantumrand, which uses ANU's quantum number generator. Unfortunately this requires an internet connection, but if you're concerned with "how random" the numbers are then this could be useful.

https://pypi.org/project/quantumrand/

Example

import quantumrand

number = quantumrand.randint(0, 9)

print(number)

Output: 4

The docs have a lot of different examples including dice rolls and a list picker.

2
  • 1
    How could anyone expect to have an internet connection? :) You could add code to catch connection exception and just return the standard random.randrange(10) in that case. Commented Mar 16, 2021 at 19:40
  • ANU website claim it's "true random". There's no such thing as "true random" in this universe, especially those numbers sent over the internet.
    – dns
    Commented Oct 8, 2021 at 17:59
0

I had better luck with this for Python 3.6

str_Key = ""                                                                                                
str_RandomKey = ""                                                                                          
for int_I in range(128):                                                                                    
      str_Key = random.choice('0123456789')
      str_RandomKey = str_RandomKey + str_Key 

Just add characters like 'ABCD' and 'abcd' or '^!~=-><' to alter the character pool to pull from, change the range to alter the number of characters generated.

1
  • Nitpick: str_RandomKey is not an integer as original poster required. Commented Sep 30, 2020 at 13:54
0

OpenTURNS allows to not only simulate the random integers but also to define the associated distribution with the UserDefined defined class.

The following simulates 12 outcomes of the distribution.

import openturns as ot
points = [[i] for i in range(10)]
distribution = ot.UserDefined(points) # By default, with equal weights.
for i in range(12):
    x = distribution.getRealization()
    print(i,x)

This prints:

0 [8]
1 [7]
2 [4]
3 [7]
4 [3]
5 [3]
6 [2]
7 [9]
8 [0]
9 [5]
10 [9]
11 [6]

The brackets are there becausex is a Point in 1-dimension. It would be easier to generate the 12 outcomes in a single call to getSample:

sample = distribution.getSample(12)

would produce:

>>> print(sample)
     [ v0 ]
 0 : [ 3  ]
 1 : [ 9  ]
 2 : [ 6  ]
 3 : [ 3  ]
 4 : [ 2  ]
 5 : [ 6  ]
 6 : [ 9  ]
 7 : [ 5  ]
 8 : [ 9  ]
 9 : [ 5  ]
10 : [ 3  ]
11 : [ 2  ]

More details on this topic are here: http://openturns.github.io/openturns/master/user_manual/_generated/openturns.UserDefined.html

0

Generate random integers between 0 and 9

With numpy

If you're OK with having a numpy dependency, then since version 1.17, numpy has Generators, which are much faster than randint/choice etc. if you want to generate a lot of random integers (e.g. more than 10000 integers). To construct it, use np.random.default_rng(). Then to generate random integers, call integers() or choice(). It is much faster than the standard library if you want to generate a large list of random numbers (e.g. to generate 1 million random integers, numpy generators are about 3 times faster than numpy's randint and about 40 times faster than stdlib's random1).

For example, to generate 1 million integers between 0 and 9, either of the following could be used.

import numpy as np
# option 1
numbers = np.random.default_rng().integers(0, 10, size=1000000)
# option 2
numbers = np.random.default_rng().choice(10, size=1000000)

By default, it uses PCG64 generator; however, if you want to use the Mersenne Twister generator which is used in random in the standard library, then you could pass its instance as a seeding sequence to default_rng() as follows.

rng = np.random.default_rng(np.random.MT19937())
numbers = rng.integers(0, 10, size=1000)

With random

If you're restricted to the standard library, and you want to generate a lot of random integers, then random.choices() is much faster than random.randint() or random.randrange().2 For example to generate 1 million random integers between 0 and 9:

import random
numbers = random.choices(range(10), k=1000000)

Some timing results1

Tested on Python 3.12 and numpy 1.26.

import timeit
import random
import numpy as np

def numpy_randint():
    return np.random.randint(0, 10, size=1000000)

def numpy_Gen_integers():
    return np.random.default_rng().integers(0, 10, size=1000000)

def numpy_Gen_choice():
    return np.random.default_rng().choice(10, size=1000000)

def random_randrange():
    return [random.randrange(10) for _ in range(1000000)]

def random_choices():
    return random.choices(range(10), k=1000000)


t1 = min(timeit.repeat(numpy_randint, number=100))      # 1.9559144999366254
t2 = min(timeit.repeat(numpy_Gen_integers, number=100)) # 0.6704635999631137
t3 = min(timeit.repeat(numpy_Gen_choice, number=100))   # 0.6696784000378102
t4 = min(timeit.repeat(random_randrange, number=100))   # 64.98768060002476
t5 = min(timeit.repeat(random_choices, number=100))     # 25.686857299879193

2 If we look at their source implementations, random.randrange() (and random.randint() because it is the former's syntactic sugar) use a while-loop to generate a pseudo-random number via _randbelow method while random.choices() calls random() once and uses it to index the population. So if a lot of pseudo-random numbers need to be generated, the cost of this while-loop adds up.

Not the answer you're looking for? Browse other questions tagged or ask your own question.