17

In Python 3.6, new module, secrets, was added.

What is the most efficient way to generate random integer in range [n, m) using this module?

I tried choice(range(n, m)), but I doubt it is the best way.

4 Answers 4

22

secrets.choice(range(n, m)) should be fine, since range is lazy on Python 3.

n + secrets.randbelow(m-n) is another option. I wouldn't use it, since it's less obviously correct.

Since secrets provides access to the SystemRandom class, with the same interface as random.Random, you can also keep your own SystemRandom instance:

my_secure_rng = secrets.SystemRandom()

and do

my_secure_rng.randrange(n, m)
1
  • my_secure_rng.randrange(1000, 9999) How to generate 4 digit number without all same digits? I need a number except any of it 1111,2222,3333,4444,5555,6666,7777,8888,9999. Mar 26, 2022 at 14:30
7

The secret module provides the same interface as random; the underlying random generator has just been changed to SystemRandom which is cryptographically strong.

In short, use it as you would random in circumstances that require a bit more security; I doubt choice suffers from performance so much to warrant your concern.

5
import secrets
num = secrets.randbelow(50)
print(num)
1
  • 3
    Please give more explanation.
    – rayryeng
    Jan 26, 2017 at 19:18
3

Not enough rep to comment but to add on to user2357112's answer if you run a quick execution time test they actually report basically identical.

Best of 3 trials with 1,000,000 loops per trial:
        randrange() 1.39906 seconds total time.
        choice() 1.39431 seconds total time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.