What is the most efficient way to toggle between 0 and 1?
What is the most efficient way to toggle between 0 and 1 ?
Share
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.
Solution using NOT
If the values are boolean, the fastest approach is to use the not operator:
Solution using subtraction
If the values are numerical, then subtraction from the total is a simple and fast way to toggle values:
Solution using XOR
If the value toggles between 0 and 1, you can use a bitwise exclusive-or:
The technique generalizes to any pair of integers. The xor-by-one step is replaced with a xor-by-precomputed-constant:
(This idea was submitted by Nick Coghlan and later generalized by @zxxc.)
Solution using a dictionary
If the values are hashable, you can use a dictionary:
Solution using a conditional expression
The slowest way is to use a conditional expression:
Solution using itertools
If you have more than two values, the itertools.cycle() function provides a generic fast way to toggle between successive values: