Generate random integers between 0 and 9

Go To StackoverFlow.com

1057

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

2010-10-22 12:48
by aneuryzm


1696

Try:

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

More info: https://docs.python.org/3/library/random.html#random.randint

2010-10-22 12:51
by kovshenin
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.htm - K48 2018-10-18 08:08


308

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

random.randint(a, b)

Return a random integer N such that a <= N <= b.

Docs: https://docs.python.org/3.1/library/random.html#random.randint

2013-05-04 17:13
by JMSamudio


99

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)
2010-10-22 12:49
by Andrew Hare


58

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.

2013-11-26 17:39
by user14372
10 or 9? I'm getting only 9 - Sigur 2017-05-11 13:52


41

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.

2016-12-06 10:29
by Chris_Rands
This would improve the answer and should be added. The more security minded answers should always be added if available - SudoKid 2018-02-07 17:15


22

Try this through random.shuffle

>>> import random
>>> nums = [x for x in range(10)]
>>> random.shuffle(nums)
>>> nums
[6, 3, 5, 4, 0, 1, 2, 9, 8, 7]
2015-10-29 09:13
by zangw
nums = range(10 - Kamejoin 2017-12-14 20:10


16

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]])
2017-02-02 06:35
by Commoner
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 2017-06-25 18:19


15

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
2017-06-03 01:45
by MSeifert
What if we want more numbers from the sequence - Gunjan naik 2017-10-03 13:43
If they should be without replacement: <code>random.sample</code>. 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 2017-10-03 13:53


10

if you want to use numpy then use the following:

import numpy as np
print(np.random.randint(0,10))
2017-01-12 03:12
by sushmit
You could tell something about "numpy" - Simón 2017-01-20 04:09
http://www.numpy.org - sushmit 2017-01-20 05:57
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 2017-01-20 16:00


9

The original question implies generating multiple random integers.

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

Many responses however only show how to get one random number, e.g. random.randint and random.choice.

Multiple Random Integers

For clarity, you can still generate multiple random numbers using those techniques by simply iterating N times:

import random


N = 5

[random.randint(0, 9) for _ in range(N)]
# [9, 7, 0, 7, 3]

[random.choice(range(10)) for _ in range(N)]
# [8, 3, 6, 8, 7]

Sample of Random Integers

Some posts demonstrate how to natively generate multiple random integers.1 Here are some options that address the implied question:

random.sample returns k unique selections from a population (without replacement):2

random.sample(range(10), k=N)
# [4, 5, 1, 2, 3]

In Python 3.6, random.choices returns k selections from a population (with replacement):

random.choices(range(10), k=N)
# [3, 2, 0, 8, 2]

See also this related post using numpy.random.choice.

1Namely @John Lawrence Aspden, @S T Mohammed, @SiddTheKid, @user14372, @zangw, et al.

2@prashanth mentions this module showing one integer.

2017-09-22 04:29
by pylang


8

>>> 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]
2017-08-10 15:48
by John Lawrence Aspden


6

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
2017-05-14 16:46
by prashanth


6

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]
2018-07-06 06:25
by Ashok Kumar Jayaraman
If you're using NumPy, you should use NumPy's random functionalities to generate this list, for example with numpy.random.randint(0, 10, size=10). The method you show is needlessly inefficient - Mark Dickinson 2018-07-06 06:44


5

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.

2017-05-15 18:29
by S T Mohammed


3

You can try this:

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

>>> [8 3 6 9 1 0 3 6 3 3 1 2 4 0 4]

Notes:

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

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

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

More information on numpy.random.uniform

More information on numpy.ndarray.astype

2018-11-28 07:56
by Siddharth Satpathy


2

I used variable to control the range

from random import randint 
numberStartRange = 1
numberEndRange = 9
randomNumber = randint(numberStartRange, numberEndRange)
print(randomNumber)

I used the print function to see the results. You can comment is out if you do not need this.

2017-09-19 11:30
by Amir Md Amiruzzaman


2

For the example that you have given (a random integer between 0 and 9), the cleanest solution is:

from random import randrange

randrange(10)
2018-10-08 14:38
by Utku
randrange returns a single number between specified range - Shital Shah 2019-01-02 01:43
@ShitalShah That is exactly what the question wants. Run the accepted answer and realize that it does the same thing - Utku 2019-01-02 02:06
@ShitalShah If you want all numbers between 0 and 9, you use range(10) - Utku 2019-01-02 02:07


2

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.

2018-11-30 18:27
by Orestis Zekai


1

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.

2018-12-11 22:49
by Richard Riehle


1

Try This,

import numpy as np

X = np.random.randint(0, 99, size=1000) # 1k random integer
2018-12-19 10:38
by Rakesh Chaudhari


-1

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.

2017-07-20 23:43
by M T Head
Ads