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?
You could use the Faker library, it's mainly used for testing, but is capable of providing a variety of fake data.
Install: https://pypi.org/project/Faker/
>>> from faker import Faker
>>> fake = Faker()
>>> fake.pybool()
True
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:
$ python -m timeit -s "from random import random" "random() < 0.5"
10000000 loops, best of 3: 0.0906 usec per loop
$ python -m timeit -s "import numpy as np" "np.random.randint(2, size=1)"
100000 loops, best of 3: 4.65 usec per loop
$ python -m timeit -s "from random import random" "test = [random() < 0.5 for i in range(1000000)]"
10 loops, best of 3: 118 msec per loop
$ python -m timeit -s "import numpy as np" "test = np.random.randint(2, size=1000000)"
100 loops, best of 3: 6.31 msec per loop
u could try this it produces randomly generated array of true and false :
a=[bool(i) for i in np.array(np.random.randint(0,2,10))]
out: [True, True, True, True, True, False, True, False, True, False]