Using the "not" Boolean Operator in Python

Using the "not" Boolean Operator in Python

by Leodanis Pozo Ramos Updated Reading time estimate 29m basics python

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 not operator works
  • How to use the not operator 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.

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:

Language: Python
>>> 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:

Language: Python
>>> 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:

Operator Logical Operation
and Conjunction
or Disjunction
not Negation

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:

Language: Python
>>> 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 if statements and while loops
  • 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:

Language: Python
>>> 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.

You can also use not with common Python objects, such as numbers, strings, lists, tuples, dictionaries, sets, user-defined objects, and so on:

Language: Python
>>> # 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 returns False or 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: None and False.
  • 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.

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:

  1. if statements let you perform conditional execution and take different courses of action based on some initial conditions.
  2. while loops 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:

Language: Python
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:

Language: Python