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?
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])If utmost speed isn't to priority then random.choice definitely reads better
$ python -m timeit -s "import random" "random.choice([True, False])" 1000000 loops, best of 3: 0.904 usec per loop $ python -m timeit -s "import random" "random.choice((True, False))" 1000000 loops, best of 3: 0.846 usec per loop $ python -m timeit -s "import random" "random.getrandbits(1)" 1000000 loops, best of 3: 0.286 usec per loop $ python -m timeit -s "import random" "bool(random.getrandbits(1))" 1000000 loops, best of 3: 0.441 usec per loop $ python -m timeit -s "import random" "not random.getrandbits(1)" 1000000 loops, best of 3: 0.308 usec per loop $ python -m timeit -s "from random import getrandbits" "not getrandbits(1)" 1000000 loops, best of 3: 0.262 usec per loop # not takes about 20us of thisAdded this one after seeing @Pavel's answer
$ python -m timeit -s "from random import random" "random() < 0.5" 10000000 loops, best of 3: 0.115 usec per loop




