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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 randomIf utmost speed isn’t to priority then
random.choicedefinitely reads better.Note that
random.choice()is slower than justchoice()(afterfrom random import choice) due to the attribute lookup.