1851

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

aneuryzm
  • 63,052
  • 100
  • 273
  • 488
  • this one is also userful: https://stackoverflow.com/questions/20936993/how-can-i-create-a-random-number-that-is-cryptographically-secure-in-python `>>> from random import SystemRandom >>> cryptogen = SystemRandom() >>> [cryptogen.randrange(3) for i in range(20)]` – Charlie Parker Nov 12 '22 at 02:15
  • 1
    this works: `import random; print(random.randint(0, 9))` – Charlie Parker Nov 12 '22 at 02:15

22 Answers22

2562

Try random.randrange:

from random import randrange
print(randrange(10))
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
kovshenin
  • 31,813
  • 4
  • 35
  • 46
  • 158
    Just a note, these are pseudorandom numbers and they are not cryptographically secure. Do not use this in any case where you don't want an attacker to guess your numbers. Use the `secrets` module for better random numbers. Reference: https://docs.python.org/3/library/random.html –  Oct 18 '18 at 08:08
  • 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. – florian.isopp Dec 01 '20 at 23:07
  • 12
    To save anyone having to navigate to the secrets module to accomplish this: `import secrets` `secrets.randbelow(10)` – sazerac Feb 05 '21 at 04:47
  • 3
    Note that the secrets module was first added to Python in version 3.6 – user3540325 Apr 30 '21 at 08:56
  • @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). – ShadowRanger May 17 '22 at 15:25
771

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).

wjandrea
  • 28,235
  • 9
  • 60
  • 81
JMSamudio
  • 7,907
  • 1
  • 12
  • 8
187

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)
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
103
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.

Community
  • 1
  • 1
user14372
  • 1,409
  • 2
  • 11
  • 12
  • 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! – WinEunuuchs2Unix Oct 24 '21 at 21:46
91

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
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
73

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.

Siddharth Satpathy
  • 2,737
  • 4
  • 29
  • 52
  • 1
    ModuleNotFoundError: No module named 'numpy' – SL5net Jan 10 '21 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`? – Unterbelichtet May 08 '21 at 13:59
  • random is a built-in module, why import it through numpy? Does numpy expand it? – LightCC Apr 27 '22 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 Jul 30 '22 at 01: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]])
Commoner
  • 1,678
  • 3
  • 19
  • 34
  • 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](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html)) – jkdev Jun 25 '17 at 18:19
30

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

pylang
  • 40,867
  • 14
  • 129
  • 121
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.

SamTheProgrammer
  • 1,051
  • 1
  • 10
  • 28
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]
zangw
  • 43,869
  • 19
  • 177
  • 214
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
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • What if we want more numbers from the sequence? – Gunjan naik Oct 03 '17 at 13:43
  • If they should be without replacement: [`random.sample`](https://docs.python.org/library/random.html#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 Oct 03 '17 at 13:53
14

if you want to use numpy then use the following:

import numpy as np
print(np.random.randint(0,10))
MSeifert
  • 145,886
  • 38
  • 333
  • 352
sushmit
  • 4,369
  • 2
  • 35
  • 38
  • 1
    You could tell something about "numpy". – Simón Jan 20 '17 at 04: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 Jan 20 '17 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]
John Lawrence Aspden
  • 17,124
  • 11
  • 67
  • 110
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)
buhtz
  • 10,774
  • 18
  • 76
  • 149
DrosnickX
  • 425
  • 5
  • 10
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]
Ashok Kumar Jayaraman
  • 2,887
  • 2
  • 32
  • 40
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.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
S T Mohammed
  • 80
  • 1
  • 2
  • 6
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
prashanth
  • 4,197
  • 4
  • 25
  • 42
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.

Orestis Zekai
  • 897
  • 1
  • 14
  • 29
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.

Community
  • 1
  • 1
rriehle
  • 362
  • 3
  • 9
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.

Dev4Hire
  • 119
  • 12
  • 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. – WestCoastProjects Mar 16 '21 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 Oct 08 '21 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.

M T Head
  • 1,085
  • 9
  • 13
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

Michael Baudin
  • 1,022
  • 10
  • 25