I am looking for the best way (fast and elegant) to get a random boolean in python (flip a coin).
For the moment I am using random.randint(0, 1)
or random.getrandbits(1)
.
Are there better choices that I am not aware of?
I am looking for the best way (fast and elegant) to get a random boolean in python (flip a coin).
For the moment I am using random.randint(0, 1)
or random.getrandbits(1)
.
Are there better choices that I am not aware of?
If you want to generate a number of random booleans you could use numpy's random module. From the documentation
will return 10 random uniform integers in the open interval [0,2). The
size
keyword specifies the number of values to generate.A new take on this question would involve the use of Faker which you can install easily with
pip
.I was curious as to how the speed of the numpy answer performed against the other answers since this was left out of the comparisons. To generate one random bool this is much slower but if you wanted to generate many then this becomes much faster:
Adam's answer is quite fast, but I found that
random.getrandbits(1)
to be quite a lot faster. If you really want a boolean instead of a long thenis still about twice as fast as
random.choice([True, False])
Both solutions need to
import random
If utmost speed isn't to priority then
random.choice
definitely reads betterAdded this one after seeing @Pavel's answer
would also work.
Found a faster method: