Best AI Code Assistant

Trusted by

100K+ Devs Worldwide

Unraveling the Mysteries of XOR in Python

XOR stands for “Exclusive OR.” In Python, as in many programming languages, XOR plays a significant role in bitwise operations and logical computations. This article demystifies the XOR in Python, shedding light on its significance and its practical applications.

Understanding the XOR Operation

The term XOR is an abbreviation for “Exclusive OR.” Its primary charm lies in its peculiar truth table, where the result is true only when the inputs differ.

Breaking Down XOR’s Truth Table

• `True XOR True` = False
• `True XOR False` = True
• `False XOR True` = True
• `False XOR False` = False

This behavior makes XOR especially valuable in scenarios where distinction is essential.

XOR: The Bedrock of Logical Operations

The Basic Principle of XOR in Python

The XOR operation is unique because it returns true only when the bits being compared are different. When both bits are the same, the result is false.

Example:

```# Bitwise XOR operation in Python
a = 5  # Binary: 0101
b = 3  # Binary: 0011

result = a ^ b
print(result)  # Outputs: 6 (Binary: 0110)

```

Deciphering XOR with Boolean Logic

When used with Boolean values, XOR in Python can be equated to inequality checks.

Example:

```True ^ False  # Outputs: True
False ^ False # Outputs: False

```

XOR in Python: Practical Applications

Data Encryption and Decryption

One of the fascinating applications of the XOR operation is in data encryption. A piece of data can be encrypted using an XOR operation, and the same operation can then be applied again to decrypt it.

Example:

```key = 129
data = "Hello"
encrypted = ''.join(chr(ord(c) ^ key) for c in data)
print(encrypted)  # Outputs: Encrypted text

# Decryption
decrypted = ''.join(chr(ord(c) ^ key) for c in encrypted)
print(decrypted)  # Outputs: Hello

```

Finding the Odd One Out

Using XOR in Python, one can efficiently identify a number that appears an odd number of times in an array.

Example:

```def find_odd_occurrence(arr):
xor_sum = 0
for num in arr:
xor_sum ^= num
return xor_sum

array = [4, 3, 4, 3, 5, 4, 3, 4, 3]
print(find_odd_occurrence(array))  # Outputs: 5

```

Conclusion: Embracing XOR for Enhanced Programming

Understanding the XOR operation deepens one’s knowledge of logical operations and bitwise manipulations in Python. Its unique properties make it invaluable in various applications, from simple data comparisons to intricate encryption mechanisms. As programmers continue to harness the power of XOR in Python

Anand Das

Anand is Co-founder and CTO of Bito. He leads technical strategy and engineering, and is our biggest user! Formerly, Anand was CTO of Eyeota, a data company acquired by Dun & Bradstreet. He is co-founder of PubMatic, where he led the building of an ad exchange system that handles over 1 Trillion bids per day.