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

PythonBooleanNegate

Python Problem Overview


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 ?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

In python, not is a boolean operator which gets the opposite of a value:

>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False

And True == 1 and False == 0 (if you need to convert it to an integer, you can use int())

Solution 3 - Python

Use not, for example:

return not myval

Solution 4 - Python

variable = not (False | variable)

is similar to

if variable == True:
    variable = False
elif variable == False:
    variable = True

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2239318View Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonTerryAView Answer on Stackoverflow
Solution 3 - PythonKlaus Byskov PedersenView Answer on Stackoverflow
Solution 4 - PythonabduljalilView Answer on Stackoverflow