Skip to Content

How To Use NOT Operator In IF Statement In Python [Code Examples]

One way to determine if one value does not equal another is to use the != comparator, but what if you’re not comparing two values – how can you determine if something is not true?

Python has an inbuilt operator aptly called not which permits a user to check a variable, or a function’s result to test if the variable or returned value is not valid.

Some classic use cases of this type of logic applied in my Python code have been checking if a file exists, other instances have been when scraping a web page and checking if the element existed on the page.

There are many other use cases, and here are some basic examples to get an idea of how this operation works:

>>> my_value = "Test string"
>>> not my_value
False

The check performed in the sample code above is determining if the variable my_value is “truthy” – meaning does Python interpret the value to be True.

How does Python know if a non-boolean value is true?

An easy way to find that out is by using the built-in Python function bool() that takes one parameter and converts it into a boolean data type, returning either True or False.

True Value Testing

To conduct your own true value testing simply open up the Python REPL and enter some values into the bool() function.

>>> bool("Test string")
True
>>> bool("")
False
>>> bool(0)
False
>>> bool(dict())
False
>>> bool({})
False
>>> bool([])
False
>>> bool([[]])
True
>>> bool(set())
False
>>> bool(tuple())
False

As you can see from the above tests there are many values which when converted to a boolean data type return False. Some of these include an empty string, the numeric value 0, an empty dictionary, an empty list (but not an empty two-dimensional list), an empty set and an empty tuple.

Using not In If Statement

The purpose of using the not operator in an if statement is to test whether the boolean returned value of a function or a variable is not True, or is False.

As detailed above, one great example where this is used in determining whether a file exists, as demonstrated in the following example:

import os

file_loc = "/output.csv"
if not os.path.exists(file_loc):
    # proceed to create file
    with open(file_loc, 'w') as f:
         # do stuff

By using the not operator you can easily read and determine what is being sought from the code.

The not operator can similarly be used on the one-liner if statement, as shown below:

>>> x = ""
>>> "Blank x" if not x else "x Not Blank"
"Blank"

Where not Doesn’t Work In if Statement

There is an instance where using the not operator in an if statement will not work, and this is in instances where an if condition is used in the list comprehension.

Applying the same logic does not work in this instance and produces a SyntaxError:

>>> my_list = ['a', None, 'c']
>>> [x for x in my_list if x not None]
  File "<input>", line 1
    [x for x in my_list if x not None]
                                 ^
SyntaxError: invalid syntax

The purpose of the above statement was to try and produce a list by filtering out the elements containing None, as you can see applying the same if condition didn’t work.

Thankfully, there is a simple solution: including the expression is in the if condition, like so:

>>> my_list = ['a', None, 'c']
>>> [x for x in my_list if not is None]
['a', 'c']

Therefore, if you find the not operator NOT working as expected in your if condition then see if including the expression is helps.

Why Not Use !?

Other languages permit the use of an exclamation mark in front of a variable or function declaration to perform the same thing as Python’s not – this is not permitted in Python, doing so would cause a SyntaxError:

>>> ! bool("")
  File "<input>", line 1
    ! bool([])
    ^
SyntaxError: invalid syntax

Therefore instead of placing the exclamation mark use the operator not in Python.

Why Not Use != True Or == False?

The other Pythonic equivalents to using the not operator is to use the more verbose expressions != True or == False, as demonstrated below:

>>> not ""
True
>>> "" != True
True
>>> "" == False
True
>>> not {}
True
>>> {} != True
True
>>> {} == False
True

As you can see from the small sample of examples above they perform the same thing.

Summary

Python provides an alternative operator to the ! syntax other language permit when determining if a variable, expression or function’s returned value is False. This operator is the expression not in Python and helps users to determine if something is False.