How to use the XOR operator in Python

XOR (exclusive or) is a bitwise operator that compares the binary representation of two numbers.

 

In Python, the XOR operator is a ^ (caret). Let's compare two integers to see how it works.

 

output = 6 ^ 4
print(output)
2

 

In the above example, Python is comparing 110 to 100 (the binary representations of 6 and 4) and returning the result.

 

If two boolean values are supplied to XOR, a boolean result will be returned:

 

output = True ^ False

print(output)
True
binary