Negate a Boolean in Python
You are given a boolean in python and you have to negate it without writing tons of lines of code.
Negation of a Boolean in Python
Some of the methods to negate a boolean in python are mentioned below:
Use not operator:
var = True print(var)
Output:
True
var2=not var print(var2)
Output:
False
Use operator.not_() function:
You can call operator.not_()
function from the operator library of python. It will return a bool which is the negation of the value passed as a parameter in the function.
import operator var = True print(operator.not_(var))
Output:
False
To use a function that requires a predicate-function such as map, filter – You can use this.
Example:
import operator var = [True, False, True, False] x=map(operator.not_, var) print(list(x))
Output:
[False, True, False, True]
Leave a Reply