python how to "negate" value : if true return false, if false return true

user2239318 picture user2239318 · Jun 18, 2013 · Viewed 171.8k times · Source
if myval == 0:
   nyval=1
if myval == 1:
   nyval=0

Is there a better way to do a toggle in python, like a nyvalue = not myval ?

Answer

Martijn Pieters picture Martijn Pieters · Jun 18, 2013

Use the not boolean operator:

nyval = not myval

not returns a boolean value (True or False):

>>> not 1
False
>>> not 0
True

If you must have an integer, cast it back:

nyval = int(not myval)

However, the python bool type is a subclass of int, so this may not be needed:

>>> int(not 0)
1
>>> int(not 1)
0
>>> not 0 == 1
True
>>> not 1 == 0
True