The Secrets of Python “Secrets”. Why and when we should not use “random”… | by Christopher Tao | Jan, 2024

Editor
2 Min Read


Why and when we should not use “random” but “secrets”?

If you work in the realm of data science and analytics, I guess you must have used the random module in Python a lot, like me. Indeed, it is very useful when we need to do some simulations, data sampling, and various other statistical algorithms.

However, there is another built-in module in Python called secrets that I believe is much less known. It does almost the same thing as random do. Even there are some function names that have exactly the same name.

Why there is such a module? When we should use secrets but not random? Please follow me in this article to get answers.

Before everything, unlike most of my other articles, there is no section called “installation”. The secrets module is built in Python. So, we can use it directly without worrying about installation.

Image by AndreasAux from Pixabay

Let’s have a look at some basic random functions in the Secrets module. Then, I’ll answer why we should NOT use random for some scenarios.

1.1 Random Choice

The choice() function in the Secrets module helps us to choose one item from a sequence, such as a list.

characters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
secrets.choice(characters)

Of course, if we run the function again, the result is likely to be different, or there is a 1/8 chance it being the same one though 🙂

In fact, a string in Python is also a sequence. So, the following is equivalent in terms of the result and probability.

You may notice that this is quite the same as the choice() function in the “random” module.

1.2 Random Integer in A Range

Share this Article
Please enter CoinGecko Free Api Key to get this plugin works.