Logical vs Bitwise operators: AND, OR, NOT
Understanding the differences in python between AND, OR and NOT logical and bitwise operators
In python, there are three logical operators: AND, OR and NOT. These same operators can also be classified as bitwise operators. The following table illustrates this in greater detail:
Note that, additionally, there are three more bitwise operators: XOR, left shift and right shift. But those are beyond the scope of this article. In this article, we will be focusing on how to use AND, OR and NOT as both logical and bitwise operators.
AND
Bitwise AND: Each bit of the output of x & y
will be 1 if the corresponding bit of both x
and y
is 1; otherwise, it's 0.
x = 5
y = 6
print(x & y)
# Output: 4
# Explanation: 101 & 110 = 100
Logical AND: This takes two operands (which can be Boolean expressions, objects or a combination) and evaluates them. If both are true, then the and
expression returns a true result. Otherwise, it returns a false result.
x = 5
y = 6
print(x > 0 and x > y)
# Output: False
# Explanation: (x > 0) is True and (x > y) is False. Hence, we get: True and False = False
OR
Bitwise OR: Each bit of the output of x | y
is 1 if the corresponding bit of either x
or y
is 1; otherwise, it's 0.
x = 5
y = 6
print(x | y)
# Output: 7
# Explanation: 101 | 110 = 111
Logical OR: Like the logical AND this also takes two operands. If either is true, then the or
expression returns a true result. Otherwise, it returns a false result.
x = 5
y = 6
print(x > 0 or x > y)
# Output: True
# Explanation: (x > 0) is True and (x > y) is False. Hence, we get: True or False = True
NOT
Bitwise NOT: It yields the bitwise inversion of its integer operand. Bitwise inversion of n
is defined as -(n+1)
.
x = 5
print(~x) # Output: -6
Logical NOT: This is also a unary operator. If you apply not
to an operand that evaluates to true, you get false as the result and vice versa.
x = 5
print(not x > 0) # Output: False
Closing thoughts
As you can see from above, AND, OR, and NOT operators give different results depending on whether they are logical or bitwise. I hope this clears up any confusion you had regarding the same.
Thanks for reading and I hope you found this article useful.