Python’s not operator allows you to invert the truth value of Boolean expressions and objects. You can use this operator in Boolean contexts, such as if statements and while loops. It also works in non-Boolean contexts, which allows you to invert the truth value of your variables.
Using the not operator effectively will help you write accurate negative Boolean expressions to control the flow of execution in your programs.
In this tutorial, you’ll learn:
- How Python’s
notoperator works - How to use the
notoperator in Boolean and non-Boolean contexts - How to use the
operator.not_()function to perform logical negation - How and when to avoid unnecessary negative logic in your code
You’ll also code a few practical examples that will allow you to better understand some of the primary use cases of the not operator and the best practices around its use. To get the most out of this tutorial, you should have some previous knowledge about Boolean logic, conditional statements, and while loops.
Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.
Working With Boolean Logic in Python
George Boole put together what is now known as Boolean algebra, which relies on true and false values. It also defines a set of Boolean operations: AND, OR, and NOT. These Boolean values and operators are helpful in programming because they help you decide the course of action in your programs.
In Python, the Boolean type, bool, is a subclass of int:
>>> issubclass(bool, int)
True
>>> help(bool)
Help on class bool in module builtins:
class bool(int)
bool(x) -> bool
...
This type has two possible values, True and False, which are built-in constants in Python and must be capitalized. Internally, Python implements them as integer numbers:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
>>> isinstance(True, int)
True
>>> isinstance(False, int)
True
>>> int(True)
1
>>> int(False)
0
Python internally implements its Boolean values as 1 for True and 0 for False. Go ahead and execute True + True in your interactive shell to see what happens.
Python provides three Boolean or logical operators:
With these operators, you can build expressions by connecting Boolean expressions with each other, objects with each other, and even Boolean expressions with objects. Python uses English words for the Boolean operators. These words are keywords of the language, so you can’t use them as identifiers without causing a syntax error.
In this tutorial, you’ll learn about Python’s not operator, which implements the logical NOT operation or negation.
Getting Started With Python’s not Operator
The not operator is the Boolean or logical operator that implements negation in Python. It’s unary, which means that it takes only one operand. The operand can be a Boolean expression or any Python object. Even user-defined objects work. The task of not is to reverse the truth value of its operand.
If you apply not to an operand that evaluates to True, then you get False as a result. If you apply not to a false operand, then you get True:
>>> not True
False
>>> not False
True
The not operator negates the truth value of its operand. A true operand returns False. A false operand returns True. These two statements uncover what is commonly known as the truth table of not:
operand |
not operand |
|---|---|
True |
False |
False |
True |
With not, you can negate the truth value of any Boolean expression or object. This functionality makes it worthwhile in several situations:
- Checking unmet conditions in the context of
ifstatements andwhileloops - Inverting the truth value of an object or expression
- Checking if a value is not in a given container
- Checking for an object’s identity
In this tutorial, you’ll find examples that cover all these use cases. To kick things off, you’ll start by learning how the not operator works with Boolean expressions and also with common Python objects.
A Boolean expression always returns a Boolean value. In Python, this kind of expression returns True or False. Say you want to check if a given numeric variable is greater than another:
>>> x = 2
>>> y = 5
>>> x > y
False
>>> not x > y
True
The expression x > y always returns False, so you can say it’s a Boolean expression. If you place not before this expression, then you get the inverse result, True.
Note: Python evaluates operators according to a strict order, commonly known as operator precedence.
For example, Python evaluates math and comparison operators first. Then it evaluates logical operators, including not:
>>> not True == False
True
>>> False == not True
File "<stdin>", line 1
False == not True
^
SyntaxError: invalid syntax
>>> False == (not True)
True
In the first example, Python evaluates the expression True == False and then negates the result by evaluating not.
In the second example, Python evaluates the equality operator (==) first and raises a SyntaxError because there’s no way to compare False and not. You can surround the expression not True with parentheses (()) to fix this problem. This quick update tells Python to evaluate the parenthesized expression first.
Among logical operators, not has higher precedence than the and operator and the or operator, which have the same precedence.
You can also use not with common Python objects, such as numbers, strings, lists, tuples, dictionaries, sets, user-defined objects, and so on:
>>> # Use "not" with numeric values
>>> not 0
True
>>> not 42
False
>>> not 0.0
True
>>> not 42.0
False
>>> not complex(0, 0)
True
>>> not complex(42, 1)
False
>>> # Use "not" with strings
>>> not ""
True
>>> not "Hello"
False
>>> # Use "not" with other data types
>>> not []
True
>>> not [1, 2, 3]
False
>>> not {}
True
>>> not {"one": 1, "two": 2}
False
In each example, not negates the truth value of its operand. To determine whether a given object is truthy or falsy, Python uses bool(), which returns True or False depending on the truth value of the object at hand.
This built-in function internally uses the following rules to figure out the truth value of its input:
By default, an object is considered true unless its class defines either a
__bool__()method that returnsFalseor a__len__()method that returns zero, when called with the object. Here are most of the built-in objects considered false:
- constants defined to be false:
NoneandFalse.- zero of any numeric type:
0,0.0,0j,Decimal(0),Fraction(0, 1)- empty sequences and collections:
'',(),[],{},set(),range(0)(Source)
Once not knows the truth value of its operand, it returns the opposite Boolean value. If the object evaluates to True, then not returns False. Otherwise, it returns True.
Note: Always returning True or False is an important difference between not and the other two Boolean operators, the and operator and the or operator.
The and operator and the or operator return one of the operands in an expression, while the not operator always returns a Boolean value:
>>> 0 and 42
0
>>> True and False
False
>>> True and 42 > 27
True
>>> 0 or 42
42
>>> True or False
True
>>> False or 42 < 27
False
>>> not 0
True
>>> not 42
False
>>> not True
False
With the and operator and the or operator, you get True or False back from the expression when one of these values explicitly results from evaluating the operands. Otherwise, you get one of the operands in the expression. On the other hand, not behaves differently, returning True or False regardless of the operand it takes.
To behave like the and operator and the or operator, the not operator would have to create and return new objects, which is often ambiguous and not always straightforward. For example, what if an expression like not "Hello" returned an empty string ("")? What would an expression like not "" return? That’s the reason why the not operator always returns True or False.
Now that you know how not works in Python, you can dive into more specific use cases of this logical operator. In the following section, you’ll learn about using not in Boolean contexts.
Using the not Operator in Boolean Contexts
Like the other two logical operators, the not operator is especially useful in Boolean contexts. In Python, you have two statements that define Boolean contexts:
ifstatements let you perform conditional execution and take different courses of action based on some initial conditions.whileloops let you perform conditional iteration and run repetitive tasks while a given condition is true.
These two structures are part of what you’d call control flow statements. They help you decide a program’s execution path. In the case of the not operator, you can use it to select the actions to take when a given condition is not met.
if Statements
You can use the not operator in an if statement to check if a given condition is not met. To make an if statement test if something didn’t happen, you can put the not operator in front of the condition at hand. Since the not operator returns the negated result, something true becomes False and the other way around.
The syntax for an if statement with the not logical operator is:
if not condition:
# Do something...
In this example, condition could be a Boolean expression or any Python object that makes sense. For example, condition can be a variable containing a string, a list, a dictionary, a set, and even a user-defined object.
If condition evaluates to false, then not returns True and the if code block runs. If condition evaluates to true, then not returns False and the if code block doesn’t execute.
A common situation is one where you use a predicate or Boolean-valued function as a condition. Say you want to check if a given number is prime before doing any further processing. In that case, you can write an is_prime() function: