Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a random boolean in python?

Tags:

python

random

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?

like image 792
Xavier V. Avatar asked Jul 26 '11 02:07

Xavier V.


People also ask

How do you generate a random Boolean?

In order to generate Random boolean in Java, we use the nextBoolean() method of the java. util. Random class. This returns the next random boolean value from the random generator sequence.

What does random () do in Python?

The random() method returns a random floating number between 0 and 1.

How do you generate random choices in Python?

Use the random. sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.


2 Answers

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 
like image 167
John La Rooy Avatar answered Sep 20 '22 13:09

John La Rooy


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

would also work.

like image 44
Adam Vandenberg Avatar answered Sep 17 '22 13:09

Adam Vandenberg