Reputation: 4629
I am looking for a short syntax that would look somewhat like x *= -1
where x
is a number, but for booleans, if it even exists. It should behave like b = not(b)
. The interested of this is being able to flip a boolean in a single line when the variable name is very long.
For example, if you have a program where you can turn on|off lamps in a house, you want to avoid writing the full thing:
self.lamps_dict["kitchen"][1] = not self.lamps_dict["kitchen"][1]
Upvotes: 5
Views: 1241
Reputation: 6056
You can use xor operator (^):
x = True
x ^= True
print(x) # False
x ^= True
print(x) # True
Edit: As suggested by Guimoute in the comments, you can even shorten this by using x ^= 1
but it will change the type of x
to an integer which might not be what you are looking for, although it will work without any problem where you use it as a condition directly, if x:
or while x:
etc.
Upvotes: 13