Logical Operators

Overview

Logical operators are key components of Python and allow for efficient comparisons between data and data types. A high level table of the different types of logical operators is included below:

Operator Description

<

less than

<=

less than or equal to

>

greater than

>=

greater than or equal to

==

equal to

!=

not equal to

not x

negation, not x

x or y

x OR y

x and y

x AND y

x is y

x and y both point to the same objects in memory

x == y

x and y have the same values

It may be important to give a quick example of the difference between == and is:

In Python the == operator is checking to see if the values are the same while the is operator is checking to see if they occupy the same space in memory. We can see this behavior in an example below:

list_1 = [1, 2, 3]
list_2 = [1, 2, 3]

print(list_1 == list_2)
print(list_1 is list_2) #Is anyone really list_2?
True
False

We can illustrate this even further if we check the ID’s associate with each list in memory. Note, the exact number may change for your Python instance:

print(id(list_1))
print(id(list_2))
4680551744
4680348800

Resources

There are lots of different articles that cover all of the types of operators available in Python. This website has a good overview of all available types for reference.