If you generate random numbers for your job or academic courses, you will find this blog post useful.
- Python
random
module - Generate a random floating point number using
random.random()
- Generate a random integer between
a
andb
usingrandom.randint()
- Generate a random number from a range of integers using
random.randrange()
- Generate a list of 15 random integers from 10 through 50
- Randomly shuffle a list of integers
- Generate random floats using
random.uniform()
- Select
n
different random items from without repitition - Generate same sequence of numbers with
random.seed
- How secure is Python's
random
module? - Generate random string with
os.urandom()
- Can I use the
random
module for security or cryptographic purposes? - How to replace
random
withsecrets
- Conclusion
Python random
module
In this blog post, we will create random numbers in Python.
Randomness is found in everywhere, especially in machine learning. Cryptography is another area that uses randomness, in relation to ciphertext. Other areas using randomness are computer simulation, randomized design, slot machines and statistical sampling. A random process is a deterministic or indeterministic process for which what we do not know is greater than what we know. This delves into the Heisenberg's Uncertainty Principle, which is a fundamental concept in quantum physics.
Python uses the random
module to generate random numbers. This is a built-in Python module. To use it, you have to import it using import random
at the top of the Python program.
import python
The random
module includes several functions. To view a list of functions in the random
module, run this in the Python shell.
help(random)
You will see the description of the random
module and a lot of info about it including description of the random.Random
class and all methods in that class. There is also information about the classe random.SystemRandom
and its methods.
Generate a random floating point number using random.random()
The random.random()
function generates a float between 0 and 1.0, not including 1.0.
0.0 <= n < 1.0
Let us print a random floating point number less than 1.
Run this code in the Python shell or on VS Code and click on the Run button.
import random
print(random.random())
Your output will be something similar to this, less than 1.0, but most likely not this exact number.
0.44034633940339185
Generate a random integer between a
and b
using random.randint()
The random.randint(a, b)
function returns a random integer which lies between a
and b
and inclusive of both.
a <= n <= b
Let us print a random number between 5 and 15.
import random
print(random.randint(5, 15))
OUTPUT:
12
Generate a random number from a range of integers using random.randrange()
The random.randrange(a, b)
function generates a random number from a range of integers, we us.
If we want to generate a random integer between a
and b
, we can use random.randrange()
a <= n <= b
Let us print a random number between 12 and 25.
import random
print(random.randrange(12, 25))
This is identical to random.randint()
, but with a difference. The third [and optional] parameter is the step.
Syntax:
random.randrange(start, stop[, step])
The step
parameter increments the number by +step
.
Let us print a random number among the multiples of 3 from 0 through 25.
The statement randrange(0, 25, 3)
returns a range and is the equivalent of range(0, 25, 3)
. Let us see what we get when we apply list to it:
>>> list(range(0, 25, 3))
[0, 3, 6, 9, 12, 15, 18, 21, 24]
Type this into the Python shell:
import random
print(random.randrange(0, 25, 3))
OUTPUT:
18
Generate a list of 15 random integers from 10 through 50
If we want to create a list of 15 random numbers from 1 through 50, we can use randint()
and combine it with list comprehension.
import random
random_numbers = [random.randint(1, 50) for _ in range(15)]
print(random_numbers)
OUTPUT:
[8, 4, 38, 36, 48, 39, 19, 37, 23, 20, 49, 45, 41, 8, 49]
Randomly shuffle a list of integers
The random.shuffle()
function is used to randomly rearrange or shuffle the list of integers.
We will create a list of 20 random numbers from 40 through 75. We will randomly shuffle the list moons
which contains [3, 5, 7, 2, 9, 4, 6, 2]
We will make it print the original list and the shuffled list.
import random
moons = [random.randrange(40, 75) for _ in range(20)]
print(moons)
random.shuffle(moons)
print(moons)
The shuffle()
function does not return anything. It shuffles all the items in moons
in-place. So, when you print the value of moons
, you get a new order of the existing items.
OUTPUT:
[51, 65, 74, 71, 71, 49, 55, 40, 41, 71, 73, 67, 53, 44, 65, 56, 54, 49, 64, 62]
[71, 41, 51, 49, 62, 64, 40, 49, 71, 65, 56, 73, 55, 74, 67, 71, 53, 44, 54, 65]
Generate random floats using random.uniform()
The random.uniform(a, b)
function returns a random float from a sequential list of numbers. This is very similar to random.randint()
.
a <= n <= b
Let us print a random float between 3 and 10.
import random
print(random.uniform(3, 10))
OUTPUT:
7.626657287029645
Select n
different random items from without repitition
The random.sample(collection, k=n)
function is used to select n
different items from the list without repitition. Both parameters collection
and k
are mandatory.
For example, let us use random.sample()
to randomly pick 3 numbers from this list.
grades = [90, 91, 68, 59, 12, 14, 99]
The code for that would be:
import random
grades = [90, 91, 68, 59, 12, 14, 99]
print(random.sample(grades, k=3))
OUTPUT:
[68, 59, 99]
If you do not enter a second parameter (for k
), it will throw an error like this:
TypeError: Random.sample() missing 1 required positional argument: 'k'
Generate same sequence of numbers with random.seed
If you want to generate the same sequence of random numbers every time the program runs, set random.seed(n)
where n can be a particular number.
import random
random.seed(10)
print(random.randint(10, 20))
random.seed(10)
print(random.randint(10, 20))
random.seed(10)
print(random.randint(10, 20))
OUTPUT:
19
19
19
As you can see, the output is exactly the same each time when you set random.seed()
with value 10
.
How secure is Python's random
module?
It is not secure. That's why Python refers to randomly generated numbers as pseudo-random numbers if generated with the random
module.
random
uses the Mersenne Twister Number Generator, also known as PRNG (Pseudo Random Number Generator) that is fast. The problem is it is not truly random and can be guessed by a hacker or malicious actor.
If random.seed()
is not called, the random number generator is seeded with random bits from the system time. This can be predictable.
Generate random string with os.urandom()
Instead of using the system time as seed, you can use os.urandom()
or random.SystemRandom()
. It is more unpredictable than the system time for getting the seed.
Also, os.urandom
and random.SystemRandom()
do not use the Mersenne Twister because they have to make system calls. Understandabily, they are slower, though more secure.
If you want to generate a random string of 16 bytes by making operating system calls, this is how you do it.
import os
print(os.urandom(16))
OUTPUT:
b'W\x9c\xde\xd0\xa3\x95\x07i\xff\x11J\xfb\xde\xca\xe4\xd8'
This is more secure than using system time.
Can I use the random
module for security or cryptographic purposes?
No. The pseudo-random generators of the random
module are meant for modeling and simulation. For generating cryptographically strong and random numbers to be used as passwords, account authentication, security tokens, etc, we should use the secret
module.
You can read more about the secret
module here.
How to replace random
with secrets
It is easy to convert your existing code that uses the random
module with the secrets
module.
To find a random number between 0 and 10 using random
:
import random
print(random.randint(10))
Now, the equivalent using secrets
.
To find a random number between 0 and 10 using secrets
:
import secrets
secrets.randbelow(10)
Conclusion
Let me know if this helped you in any way. If you would like more information about generating random numbers to be added, please email me or comment below. Thanks for reading.
Related Posts
If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom. You can also post questions in our Facebook group. Thank you.