Python XOR: How to Use Bitwise XOR Operator

In Python, the XOR (exclusive OR) operator is a bitwise operator defined by the caret symbol ^.

This operator takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits.

It returns 1 when either of the operands is 1, otherwise 0.

The XOR operator can be used for various purposes, including cryptography, data manipulation, and solving certain algorithmic problems.

Truth table for XOR (binary)

Example 1: Basic XOR Operations

Visual Representation

Basic XOR Operations

a = 10 # In binary: 1010
b = 7 # In binary: 0111

result = a ^ b # 1010 XOR 0111 = 1101 in binary, which is 13 in decimal

print(result) 

Output

13

Example 2: Swapping Two Variables

x = 10
y = 7

print('Before swapping: ')
print('The value of x is: ', x) 
print('The value of y is: ', y)

x = x ^ y
y = x ^ y
x = x ^ y

print('After swapping: ')
print('The value of x is: ', x) 
print('The value of y is: ', y)

Output

Before swapping: 
The value of x is: 10
The value of y is: 7
After swapping: 
The value of x is: 7
The value of y is: 10

Example 3: Performing XOR on booleans

XOR returns True if the two boolean values are different (one True and one False), and False if they are the same (both True or both False).

a = True
b = False

result = a ^ b
print(result) 

a = True
b = True

result = a ^ b
print(result) 

a = False
b = False

result = a ^ b
print(result)

a = False
b = True

result = a ^ b
print(result) 

Output

True
False
False
True

What is the difference between XOR and OR?

Here’s a comparison in tabular format:

Input A Input B XOR (A ^ B) OR (A | B)
0 0 0 0
0 1 1 1
1 0 1 1
1 1 0 1

The main difference between XOR and OR operators is that XOR returns True if exactly one of the inputs is 1, whereas OR returns 1 (True) if at least one of the inputs is 1.

The other difference is that XOR is an exclusive operator, whereas OR is an inclusive operator.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.