Python If with NOT Operator

Python If with not is used to check whether a variable is empty or not. This variable could be Boolean, List, Dictionary, Tuple ,String or set.

Let us go through the examples of each. Note - Below code has been tested on Python 3.

Python Check if not boolean

In [2]:
x = True
if x:
    print(x)
True

If not can check for any expression too.

In [5]:
x = 4
if not x==5:
    print("%d is not 5"%x)
4 is not 5

Below expression will become true if x is 0.

In [3]:
x = 0
if not 0:
    print(x)
else:
    print()
0

Note: Above will true if x is any value other than 0.

In [4]:
x = -2
if not x:
    print(0)
else:
    print('not 0')
not 0

Python Check if not String

With "if not", we can check if string is empty

In [6]:
x = ""
if not x:
    print("x is empty")
else:
    print(x)
x is empty

Python Check if not None

In [9]:
x = None
if x is not None:
    print("not none")
else:
    print(x)
None

Python Check if not Dictionary

In [11]:
x = {}
if not x:
    print(x, "is empty")
else:
    print(x,"not empty")
{} is empty

Python Check if not Key in Dictionary

Let us check for key 'b' with Python 'if not'

In [12]:
x = {'a':1,'b':2,'c':3}
if 'b' not in x:
    print('key b is not present in x')
else:
    print('b is present')
b is present

Python Check if not List

If not works on the same way on Python list too as it works on Dictionaries.

In [13]:
x = [1,2,3,4,5,]
if not x:
    print('List is empty')
else:
    print(x)
[1, 2, 3, 4, 5]

Python Check if Element not in List

In [14]:
x = [1,2,3,4,5]
if 6 not in x:
    print('6 is not in List')
else:
    print('6 is present in list')
6 is not in List
In [16]:
x = ["a b","c d"]
if "a b" not in x:
    print('"a b" is not present in List')
else:
    print('"a b" is present in list')
"a b" is present in list

Python Check If not Set

In this example, we will use Python if not, to check if set is empty.

In [17]:
x = set({})
if not x:
    print('Set is empty.')
else:
    print(x)
Set is empty.

Python Check if value not in Set

In [19]:
x = set({'a','b','c'})
if 'd' not in x:
    print('d not in x')
else:
    print('d in x')
d not in x

Python Check if not Tuple

In this example, we will use Python if not, to check if tuple is empty.

In [20]:
x = tuple()

if not x:
    print('Tuple is empty.')
else:
    print(x)
Tuple is empty.

Python Check if not value in Tuple

In [24]:
x = ("a","b","c")
In [25]:
if 'd' not in x:
    print('d not in x')
else:
    PRint('d in x')
d not in x

Summary: Python "if not" operator is very easy to use. I hope the above examples made the usage of Python "if not" clearer.