How to do XOR in Python

Learn how to perform XOR operations in Python. Discover different methods, real-world applications, common errors, and debugging tips.

How to do XOR in Python
Published on: 
Tue
Feb 24, 2026
Updated on: 
Mon
Apr 6, 2026
The Replit Team

The XOR operation in Python, performed with the ^ operator, is a powerful bitwise tool. It's essential for tasks like data encryption, error detection, and simple algorithm design.

In this article, you'll explore several techniques to use the ^ operator. You'll get practical implementation tips, examine real-world applications, and receive advice to help you debug your XOR logic effectively.

Basic XOR operation using the ^ operator

a = 5 # 101 in binary
b = 3 # 011 in binary
result = a ^ b
print(f"{a} XOR {b} = {result}")--OUTPUT--5 XOR 3 = 6

The code snippet demonstrates the bitwise nature of the ^ operator. It doesn't just work on the numbers 5 and 3; it compares their binary representations—101 and 011—bit by bit. Understanding converting binary to integer helps clarify how these operations work at the bit level.

The XOR logic returns a 1 only when the corresponding bits are different. The comparison works like this:

  • 1 XOR 01
  • 0 XOR 11
  • 1 XOR 10

This process yields the binary value 110, which is why the final result is the decimal number 6.

Working with binary XOR operations

This same bit-by-bit logic extends beyond two numbers, allowing you to work with multiple values, booleans, and perform direct bit manipulation.

Performing XOR on multiple values

values = [5, 3, 9, 12]
result = 0
for val in values:
result ^= val
print(f"XOR of {values} = {result}")--OUTPUT--XOR of [5, 3, 9, 12] = 15

The XOR operator isn't limited to just two numbers; you can apply it cumulatively to a sequence. The code iterates through the list, using result ^= val—a compact way of writing result = result ^ val—to continuously update a running total.

This technique works reliably for a couple of key reasons:

  • It starts with an initial value of 0. Since any number XORed with 0 is itself, this correctly seeds the calculation.
  • The XOR operation is associative, meaning the order in which the numbers are processed doesn't change the final outcome.

XOR with boolean values using the != operator

a = True
b = False
xor_result = a != b
print(f"{a} XOR {b} = {xor_result}")
print(f"{a} XOR {a} = {a != a}")--OUTPUT--True XOR False = True
True XOR True = False

When you're working with booleans, the != (not equal) operator functions as a logical XOR. It's a more direct and Pythonic way to get the same result you'd see with the bitwise ^ operator on integers 1 and 0.

  • The expression is True only when the two values are different, like True != False.
  • It becomes False if the values are identical, such as True != True.

This behavior perfectly mirrors the core XOR principle: the output is true only when the inputs differ. This is in contrast to logical OR operations, which return true when at least one input is true.

Bit manipulation with XOR

num = 45 # 00101101 in binary
mask = 0b00001111 # Binary literal for 15
toggled = num ^ mask
print(f"Original: {num}, After XOR with {mask}: {toggled}")--OUTPUT--Original: 45, After XOR with 15: 34

You can use the ^ operator for precise bit manipulation, like toggling specific bits in a number. This is done with a "bitmask"—a value created to modify another. Here, the mask is 0b00001111.

  • Any bit in num that aligns with a 1 in the mask gets flipped.
  • Any bit that aligns with a 0 in the mask remains unchanged.

This selective toggling is why applying the mask to 45 flips its last four bits, producing the result 34.

Advanced XOR techniques

Building on these fundamental operations, you can apply XOR to solve more complex problems, from functional programming to data security and algorithmic puzzles.

Using the operator module for XOR

import operator
a, b, c = 10, 7, 5
result = operator.xor(a, operator.xor(b, c))
print(f"XOR of {a}, {b}, and {c} = {result}")--OUTPUT--XOR of 10, 7, and 5 = 8

The operator module offers a function-based equivalent for Python's intrinsic operators. In this case, operator.xor() is a direct replacement for the ^ symbol, performing the exact same bitwise calculation.

This approach is especially useful in functional programming. It allows you to treat the XOR operation as a first-class object, which you can then pass to higher-order functions like functools.reduce to apply it cumulatively across a sequence of values.

Simple encryption with XOR

message = "Hello"
key = 42
encrypted = ''.join(chr(ord(char) ^ key) for char in message)
decrypted = ''.join(chr(ord(char) ^ key) for char in encrypted)
print(f"Encrypted: {encrypted}, Decrypted: {decrypted}")--OUTPUT--Encrypted: *-88;, Decrypted: Hello

XOR's unique reversibility makes it a classic tool for simple encryption. The process is straightforward and relies on a key property of the ^ operator.

  • Each character in the message is converted to its numerical value using ord().
  • This number is then XORed with a secret key.
  • Applying the exact same operation to the encrypted text with the same key restores the original message.

This works because any value XORed with a key twice returns to its original state. It’s a great demonstration, but remember this method isn't secure enough for real-world data protection.

Finding the missing number with XOR

def find_missing(nums, n):
expected_xor = 0
for i in range(1, n+1):
expected_xor ^= i
actual_xor = 0
for num in nums:
actual_xor ^= num
return expected_xor ^ actual_xor

print(find_missing([1, 2, 4, 5], 5))--OUTPUT--3

This clever algorithm leverages a key property of XOR: any number XORed with itself is zero. The find_missing function first calculates the XOR sum of the complete sequence of numbers. It then does the same for the list you provide.

  • When these two results are XORed together using the ^ operator, all the numbers present in both sequences cancel out.
  • This leaves you with only the number that was missing from the input list.

It’s an efficient way to pinpoint a missing value without sorting or extra storage.

Move faster with Replit

Replit is an AI-powered development platform where all Python dependencies pre-installed, so you can skip setup and start coding instantly. It’s designed to help you move from learning individual techniques, like the ^ operator, to building complete applications with Agent 4.

Instead of piecing together code, you can describe the app you want to build, and Agent 4 will take it from idea to working product. Here are a few examples related to the XOR operations you've just seen:

  • A simple encryption tool that uses an XOR cipher to secure and decrypt messages with a secret key.
  • A data integrity utility that finds a missing number in a sequence, perfect for verifying datasets.
  • A configuration tool that uses bitmasks to toggle specific feature flags in a numerical setting.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

While the ^ operator is powerful, a few common pitfalls can trip you up, from operator confusion to tricky type errors and algorithmic bugs.

Common error: Mistaking ^ for exponentiation

In many languages, the ^ symbol is used for exponentiation, which can cause confusion. In Python, however, ^ is exclusively for the bitwise XOR operation. Using it to calculate a power will lead to an incorrect result, as the following code demonstrates.

base = 2
exponent = 3
result = base ^ exponent # This performs XOR, not exponentiation
print(f"{base} raised to the power of {exponent} = {result}")

Instead of calculating a power, the ^ operator compares the binary representations of 2 and 3. This bitwise XOR operation results in 1. The following snippet shows the correct operator for exponentiation in Python.

base = 2
exponent = 3
result = base ** exponent # Use ** for exponentiation
print(f"{base} raised to the power of {exponent} = {result}")

To correctly calculate powers in Python, you must use the ** operator, not ^. The expression base ** exponent correctly computes 2 raised to the power of 3, yielding 8. It's a frequent mix-up, especially for developers familiar with other languages where ^ signifies exponentiation. For more details on calculating exponents in Python, always double-check your operators when performing mathematical calculations to avoid this subtle but significant bug in your logic.

Debugging XOR type errors in Python

Debugging XOR type errors in Python

The ^ operator is strictly for bitwise operations on integers. A common mistake is trying to use it on other data types, like strings, which Python doesn't allow. This mismatch will immediately raise a TypeError, stopping your program.

The following code demonstrates what happens when you attempt to XOR a string with an integer, triggering this specific error.

value = "10" # String representation of a number
mask = 5
result = value ^ mask # TypeError: unsupported operand type(s)
print(f"Result: {result}")

This TypeError occurs because the ^ operator cannot work with a string like "10". Python requires both values to be integers for bitwise operations. The following code demonstrates the correct approach to resolve this.

value = "10" # String representation of a number
mask = 5
result = int(value) ^ mask # Convert to integer first
print(f"Result: {result}")

The solution is to explicitly convert the string to an integer using the int() function. By changing the code to int(value) ^ mask, you provide the ^ operator with the integer operands it requires. Understanding type casting in Python is essential for these conversions. Keep an eye out for this TypeError when you're working with data from user input or files, as that data is often read as strings even when it looks like numbers. This simple conversion ensures your bitwise logic runs smoothly.

Troubleshooting the XOR swap algorithm

The XOR swap is a clever, memory-efficient trick for swapping two variables using the ^ operator without a temporary one. While it seems straightforward, a subtle logic error in the sequence of operations can lead to incorrect results, completely losing one of the original values.

The following code demonstrates this common mistake, where the order of assignment goes wrong and corrupts the final output.

a = 5
b = 10
a = a ^ b
b = a # Incorrect: b is now equal to (a^b)
a = a ^ b # a becomes (a^b)^(a^b) which is 0
print(f"a = {a}, b = {b}") # Values not properly swapped

The problem is the line b = a, which overwrites b with an intermediate value. This makes the final a = a ^ b operation cancel itself out, wiping out the original value. See the correct implementation below.

a = 5
b = 10
a = a ^ b # a becomes (a^b)
b = a ^ b # b becomes (a^b)^b which equals original a
a = a ^ b # a becomes (a^b)^a which equals original b
print(f"a = {a}, b = {b}") # Values successfully swapped

The solution hinges on the correct sequence of XOR assignments. The expression a = a ^ b first stores a combined value. Next, b = a ^ b uses this new value to restore the original a into the variable b. Finally, a = a ^ b uses the updated b to restore the original b into a. This three-step process correctly swaps the variables. Always verify the order of operations when implementing this algorithm to avoid data loss.

Real-world applications

Once you've navigated the common pitfalls, you can use the ^ operator for practical tasks like toggling UI states and verifying data integrity.

Using ^ for toggling UI states

Because the ^ operator can flip individual bits without affecting others, it’s an efficient way to manage multiple UI states within a single variable.

UI_STATES = {"dark_mode": 1, "sidebar": 2, "fullscreen": 4}
current_state = 0 # No features active

# Toggle dark mode and sidebar on
current_state ^= UI_STATES["dark_mode"]
current_state ^= UI_STATES["sidebar"]
print(f"Current UI state: {current_state}")

This snippet uses a dictionary, UI_STATES, where each feature is assigned a power of two. This technique ensures every state corresponds to a unique bit. The current_state variable starts at 0, meaning no features are active.

  • The code then applies the ^= operator to combine the dark_mode (value 1) and sidebar (value 2) states.
  • The final current_state is 3, the result of 0 ^ 1 ^ 2. This single integer now compactly represents the combined state of both active features.

Using ^ for data integrity verification

The ^ operator can create a simple checksum, giving you a fast way to verify data integrity by detecting if even a single byte has been altered.

def xor_checksum(data):
result = 0
for byte in data:
result ^= byte
return result

original_data = [10, 20, 30, 40]
checksum = xor_checksum(original_data)
print(f"XOR checksum: {checksum}")

# Check if data is corrupted
modified_data = [10, 20, 31, 40] # One value changed
print(f"Data integrity check: {xor_checksum(modified_data) == checksum}")

The xor_checksum function uses the cumulative property of the ^ operator to create a condensed representation of the data. Each number in the list is folded into the result, which starts at 0 to ensure the calculation is seeded correctly.

  • Because XOR is its own inverse, the final checksum is sensitive to every bit in the input.
  • Changing even one value, like from 30 to 31, alters the final result completely.

The final comparison checks if this calculated signature matches the original. A False result proves the data has been altered.

Get started with Replit

Turn what you've learned into a real tool. Give Replit Agent a prompt like “a file checksum utility using XOR” or “a simple text encryption app that uses an XOR cipher.”

Replit Agent writes the code, tests for errors, and deploys the app, handling the entire development cycle for you. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.