Get a random boolean in python?

PythonRandom

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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 then

bool(random.getrandbits(1))

is 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 better.

Note that random.choice() is slower than just choice() (after from random import choice) due to the attribute lookup.

$ python3 --version
Python 3.9.7
$ python3 -m timeit -s "from random import choice" "choice([True, False])"
1000000 loops, best of 5: 376 nsec per loop
$ python3 -m timeit -s "from random import choice" "choice((True, False))"
1000000 loops, best of 5: 352 nsec per loop
$ python3 -m timeit -s "from random import getrandbits" "getrandbits(1)"
10000000 loops, best of 5: 33.7 nsec per loop
$ python3 -m timeit -s "from random import getrandbits" "bool(getrandbits(1))"
5000000 loops, best of 5: 89.5 nsec per loop
$ python3 -m timeit -s "from random import getrandbits" "not getrandbits(1)"
5000000 loops, best of 5: 46.3 nsec per loop
$ python3 -m timeit -s "from random import random" "random() < 0.5"
5000000 loops, best of 5: 46.4 nsec per loop

Solution 2 - Python

import random
random.choice([True, False])

would also work.

Solution 3 - Python

Found a faster method:

$ python -m timeit -s "from random import getrandbits" "not getrandbits(1)"
10000000 loops, best of 3: 0.222 usec per loop
$ python -m timeit -s "from random import random" "True if random() > 0.5 else False"
10000000 loops, best of 3: 0.0786 usec per loop
$ python -m timeit -s "from random import random" "random() < 0.5"
10000000 loops, best of 3: 0.0579 usec per loop

Solution 4 - Python

If you want to generate a number of random booleans you could use numpy's random module. From the documentation

np.random.randint(2, size=10)

will return 10 random uniform integers in the open interval [0,2). The size keyword specifies the number of values to generate.

Solution 5 - Python

I like

 np.random.rand() > .5

Solution 6 - Python

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

Solution 7 - Python

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

Solution 8 - Python

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]

Solution 9 - Python

A new take on this question would involve the use of Faker which you can install easily with pip.

from faker import Factory
 
#----------------------------------------------------------------------
def create_values(fake):
    """"""
    print fake.boolean(chance_of_getting_true=50) # True
    print fake.random_int(min=0, max=1) # 1
 
if __name__ == "__main__":
    fake = Factory.create()
    create_values(fake)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionXavier V.View Question on Stackoverflow
Solution 1 - PythonJohn La RooyView Answer on Stackoverflow
Solution 2 - PythonAdam VandenbergView Answer on Stackoverflow
Solution 3 - PythonPavel RadchenkoView Answer on Stackoverflow
Solution 4 - PythonChrisView Answer on Stackoverflow
Solution 5 - PythonMaartenView Answer on Stackoverflow
Solution 6 - PythonojunkView Answer on Stackoverflow
Solution 7 - PythonPartibanView Answer on Stackoverflow
Solution 8 - Pythongourav naikView Answer on Stackoverflow
Solution 9 - PythonAltheaView Answer on Stackoverflow