How to XOR in Python

When working with binary operations in Python, understanding how to perform an XOR (exclusive OR) is essential. Whether you are writing cryptographic functions, solving algorithmic problems, or simply working with bits and bytes, XOR can be an incredibly useful operation. Unlike other logical operations, XOR returns True only when the two inputs are different. If you’re curious about how to use XOR in Python, this guide will break it down in a way that’s easy to follow, even for beginners.

Understanding XOR Logic

XOR stands for ‘exclusive OR’. It is a binary operator that takes two bits and returns one bit. The result is1if the bits are different, and0if the bits are the same. This behavior can be summarized in the following table:

  • 0 XOR 0 = 0
  • 0 XOR 1 = 1
  • 1 XOR 0 = 1
  • 1 XOR 1 = 0

This logic is commonly used in programming for tasks such as toggling bits, encryption, and finding unique elements in a list. In Python, XOR is represented using the caret symbol (^).

Using XOR with Integers

Basic Example

To apply the XOR operation between two integers in Python, simply use the^operator. For example:

result = 5 ^ 3 print(result) # Output: 6

Here, 5 in binary is0101and 3 is0011. XORing them gives0110, which is 6 in decimal. This is the most direct way to perform XOR in Python.

Common Uses of XOR with Integers

  • Swapping two variables without a temporary variable:
a = 10 b = 15 a = a ^ b b = a ^ b a = a ^ b print(a, b) # Output: 15 10
  • Finding a single non-duplicate in a list where all other elements appear twice:
nums = [2, 3, 5, 4, 5, 3, 4] unique = 0 for num in nums: unique ^= num print(unique) # Output: 2

Using XOR with Boolean Values

Python also allows XOR with boolean values. The caret operator works with booleans as well:

print(True ^ False) # Output: True print(True ^ True) # Output: False

While this is syntactically valid, it’s generally more readable to use the!=operator for boolean XOR:

print(True != False) # Output: True print(True != True) # Output: False

Bitwise XOR vs Logical XOR

It’s important to distinguish between bitwise XOR and logical XOR. The^operator performs bitwise XOR on integers and logical XOR on booleans. Python does not have a built-in logical XOR operator for multiple boolean expressions, so combining conditions needs to be done manually:

# Emulating logical XOR a = True b = False print((a and not b) or (not a and b)) # Output: True

Performing XOR on Bytes

XORing Byte Strings

XOR is especially useful when working with byte strings, particularly in encryption or checksum algorithms. In Python, byte strings can be XORed using a loop or a list comprehension:

def xorbytes(b1, b2): return bytes([x ^ y for x, y in zip(b1, b2)]) result = xorbytes(b'hello', b'world') print(result)

Note that both byte strings must be of the same length. If not, you’ll get an error or incorrect results. Always ensure data alignment before XORing.

XOR in Cryptographic Applications

XOR is fundamental in simple cryptographic algorithms. For example, a one-time pad uses XOR to encrypt and decrypt data with a key:

def xorcipher(data, key): return bytes([d ^ k for d, k in zip(data, key)]) plaintext = b'secret' key = b'random' ciphertext = xorcipher(plaintext, key) print(ciphertext) decrypted = xorcipher(ciphertext, key) print(decrypted) # Output: b'secret'

This works because XOR is its own inverse: applying XOR twice with the same key restores the original value.

XOR in Python for Problem Solving

Python programmers often use XOR for solving interview and competitive programming problems. A classic example is finding two unique elements in an array where all others appear twice. The XOR trick helps reduce time complexity:

def findtwounique(nums): xorall = 0 for num in nums: xorall ^= num rightmostsetbit = xorall & -xorall num1 = num2 = 0 for num in nums: if num & rightmostsetbit: num1 ^= num else: num2 ^= num return num1, num2 print(findtwounique([1, 2, 3, 2, 1, 4])) # Output: (3, 4)

This demonstrates how XOR can be a powerful tool when used strategically in data manipulation.

Things to Keep in Mind

  • Use^for XOR in Python, whether dealing with integers or booleans.
  • XOR is commutative and associative:a ^ b == b ^ aanda ^ (b ^ c) == (a ^ b) ^ c.
  • It’s useful for toggling bits, swapping variables, and finding unique elements.
  • When working with bytes, ensure data alignment to avoid mismatches.

Mastering how to XOR in Python is a valuable skill that can streamline solutions in data manipulation, cryptography, and algorithm design. Whether you’re using it to simplify logic, encrypt messages, or solve interview problems, the XOR operation is more than just a bitwise operator it’s a tool of efficiency and creativity. With practice, you’ll start to recognize situations where XOR isn’t just helpful, but the smartest approach available.