5

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]
Guimoute
  • 4,407
  • 3
  • 12
  • 28

1 Answers1

13

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.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Asocia
  • 5,935
  • 2
  • 21
  • 46