You Might Have Misused Python Random

4 min readDec 27, 2020
Photo by Lucas Santos on Unsplash


Python random module provides a convenient way for generating pseudo-random numbers in case you need some unpredictable results for your application such as the computer games, a lucky draw system or even the shuffling logic for your music player. Since it provides various functions to generate results in “unpredictable” manner, developers attempted to use this feature to produce random password or authentication token for security purpose without understanding of it’s fundamental implementation. In this article, we will be discussing how the Python random module has been misunderstood and misused for the scenarios which it shall not be used.

Basic usage of Python random module

Let’s take a look at some basic usage of this module. You can use it to generate random integers, float numbers or bytes as per below:

#Generate a random integer between 1 to 10 
#generate a random floating point number between 0 to 1 random.random()
#Generate random number between 1 to 2 in uniform distribution
random.uniform(1, 2)
#Generate random number between 1 to 100, with step as 2
random.randrange(1, 100, 2)
#Generate random bytes, available in Python version 3.9 random.randbytes(8)
#Generate a integer within 8 bits

And shuffling or sampling the items in a sequence can be achieved easily with below:

slangs = ["Boomer", "Cap", "Basic", "Retweet", "Fit", "Fr", "Clout"]random.shuffle(slangs) 
#['Fit', 'Basic', 'Fr', 'Clout', 'Cap', 'Retweet', 'Boomer']

random.sample(slangs, k=5)
#['Fit', 'Fr', 'Clout', 'Retweet', 'Basic']

You can also use the choice function to choose a random option from a given sequence, for instance:

random.choice(["Boomer", "Cap", "Basic", "Retweet", "Fit", "Fr", "Clout"])

With this function, It’s easy to implement a lucky draw logic where all the participants’ name are passed in and a winner is…


Resources and tutorials for python, data science and automation solutions