Skip to content

Python XOR operator | Code

  • by

In Python, XOR is a bitwise operator that is also known as Exclusive OR. The symbol for XOR in Python is ‘^’ and in mathematics, its symbol is ‘⊕’.

xor_num = num1 ^ num2

You can use it with the XOR of two integers, the XOR of two booleans, Swapping two numbers using XOR, etc.

Python XOR operator

In the simple example, code used between two integers, the XOR operator returns an integer and a boolean. When performing XOR on two booleans, True is treated as 1, and False is treated as 0. Thus, XOR between two booleans returns a boolean.

output = 19 ^ 21
print("XOR", output)

result = True ^ False
print("XOR", result)

Output:

Python XOR operator

How do you get the logical xor of two variables in Python?

Answer: Bitwise exclusive-or is already built-in to Python, in the operator module (which is identical to the ^ operator):

from operator import xor
xor(bool(a), bool(b))  # Note: converting to bools is essential

Here’s how the XOR operator works in Python:

  • True ^ True evaluates to False
  • True ^ False evaluates to True
  • False ^ True evaluates to True
  • False ^ False evaluates to False

Example:

# XOR operator examples
print(True ^ True)   # Output: False
print(True ^ False)  # Output: True
print(False ^ True)  # Output: True
print(False ^ False) # Output: False

You can use the XOR operator in boolean expressions or to perform bitwise operations on integers.

Comment if you have any doubts or suggestions on this Python operator topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *