Randomness in Python: A Comprehensive Guide
Computers can’t generate a truly random number

Randomness is one of the essential features of the world. In software development and data science, we usually need to handle random things.
However, computers are inherently not good at random stuff. As long as we use a human-defined algorithm to get a number, the machine will follow the same algorithm every time, so the results are predictable and lack randomness.
Therefore, computers can’t generate a truly random number, since they are designed to be deterministic. But using some tricks to generate pseudo-random numbers is totally possible. Typically, a pseudo-random generator starts with a “seed” number and then follows a pattern. So as long as the “seed” is different every time, the generated number will be different as well.
There are some choices of the pseudo-random generator. Python uses the Mersenne Twister as the core generator in its built-in random module. This article will dive into the random module and give you a comprehensive guide about the randomness in Python.
“One thing that traditional computer systems aren’t good at is coin flipping.” — Steve Ward, Professor of Computer Science and Engineering at MIT.
Understand the Seed of Randomness
By default, Python’s random number generator uses the current system time as the seed. It’s a clever choice. Cause the current system time is always different at any time.
Python also gives us the flexibility to change the seed by the random.seed() function. To confirm the previous theory, a pseudo-random generator relies on a seed number and then follows a certain pattern, we can specify the same seed value twice and check out what will happen:
>>> random.seed(1)
>>> random.random()
0.13436424411240122
>>> random.seed(1)
>>> random.random()
0.13436424411240122As the above code shows, as long as the seeds are the same, the results will be the same as well. This explains why it’s called “pseudo-random”.
There are two more methods worth to mention: random.getstate() and random.setstate(). As their names imply, the first one can help us get the current internal state of the generator. And the second one can be used to set a specific state of the generator. They are useful for some cases:
>>> import random
>>> state=random.getstate()
>>> random.random()
0.2550690257394217
>>>random.random()
0.49543508709194095
>>> random.setstate(state)
>>> random.random()
0.2550690257394217As demonstrated above, we can exactly control when to get the same “random” number as a previous one with the help of getstate() and setstate() methods.
Generate Random Numbers
In most cases, we need to generate two types of numbers: int and float.
Generate an integer randomly
To get an integer in a certain range, we can use the randrange(start, stop, step) method.
>>> import random
>>> random.randrange(1,3)
2
>>> random.randrange(1,3)
1
>>> random.randrange(1,3)
1This method, just like the range() method in Python, doesn’t include the end point.
We can also specify the third parameter step and it’s very convenient in some cases. For example, the following program will only generate even integers between 0 and 10:
>>> random.randrange(0,11,2)
8Another simplified choice is the randint(start,stop) method. We can treat it as an alias for randrange(start, stop+1), since it includes the end point.
>>> import random
>>> random.randint(1,3)
2
>>> random.randint(1,3)
3
>>> random.randint(1,3)
1Generate a random float number
Basically, the random() function will generate a random float number between 0 and 1. (excluding 1).
>>> random.random()
0.6596661752737053If we would like to specify the range, we can use another method called uniform:
>>> random.uniform(0.5, 3.1)
2.6947163565041437Generate a random float number based on a specific distribution
Sometimes, we may need to generate random numbers under more complex conditions, such as based on a specific statistic distribution. Python, as a user-friendly language, also has built-in methods for common distributions. These are super useful for data science.
For example, the gauss(mu, sigma) method can return a random floating point number based on the Gaussian distribution. Specifically, mu is the mean, and sigma is the standard deviation.
>>> random.gauss(0,1)
0.7388503877433976There are many other methods which can generate floating point numbers based on different statistical distributions, to name a few:
betavariate(): Beta distributionexpovariate(): Exponential distributiongammavariate(): Gamma distributionlognormvariate(): Log normal distributionnormalvariate(): Normal distributionvonmisesvariate(): von Mises distributionparetovariate(): Pareto distributionweibullvariate():Weibull distribution
Pick an Item Randomly
There are 3 useful methods for this type of purpose:
First of all, the choice() method can help us pick one item from an iterable object easily:
>>> leaders=['Yang','Tim','Elon']
>>> random.choice(leaders)
'Yang'Secondly, the sample() method can do a bit more. We can set how many items we would like to pick randomly.
>>> leaders=['Yang','Tim','Elon']
>>> random.sample(leaders,2)
['Elon', 'Yang']Last but not least, we can apply different weights for every item for the random choices. This is the choices() method’s showcase:
>>> leaders=['Yang','Tim','Elon']
>>> random.choices(leaders,weights=[3,1,1],k=5)
['Tim', 'Elon', 'Yang', 'Yang', 'Yang']Shuffle the Order of Iterable Objects
This operation is simple, cause we can use the shuffle method directly:
>>> nums=[1,2,3,4,5]
>>> random.shuffle(nums)
>>> nums
[4, 3, 2, 5, 1]As shown above, the shuffle method won’t return anything. The changes will affect the nums list directly. Any iterable objects, such as lists, tuples and so on, can be shuffled by it.
Key Takeaways
Computers cannot generate truly random numbers. But we can still get pseudo-random numbers and they are good enough for our daily development scenarios.
Python’s built-in random module gives us lots of options to handle random stuff. To summarise, the following tasks are easy for us:
- Control the seed of the pseudo-random generator
- Generate random numbers
- Pick items randomly from an iterable object
- Shuffle an iterable object randomly
Thanks for reading. If you like it, please follow me and become a Medium member to enjoy more interesting stories about programming and technologies!
Here is another interesting article about random numbers generation in Python:





