XOR in Python is the caret operator ^. For two integers it returns a number whose binary digits are 1 only where the inputs' digits differ, so 5 ^ 3 returns 6.
>>> 5 ^ 3
6
>>> 5 ^ 5
0
>>> 5 ^ 0
5
The Python language reference says ^ "yields the bitwise XOR (exclusive OR) of its arguments, which must be integers or one of them must be a custom object overriding __xor__() or __rxor__() special methods." The rest of this article shows what that means for integers, bools and sets, and how to get a logical XOR when that is what you need.
How XOR works: the truth table
XOR means "exclusive or": the result is true when exactly one input is true, and false when both are the same.
| a | b | a ^ b |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
On whole numbers Python applies that table to every bit position at once. Take 12 ^ 10:
1100 (12)
^ 1010 (10)
----
0110 (6)
>>> 12 ^ 10
6
>>> bin(12 ^ 10)
'0b110'
Two properties make XOR useful. Anything XOR itself is 0 (x ^ x == 0), and anything XOR 0 is itself (x ^ 0 == x). Together they mean XOR is its own inverse: (x ^ k) ^ k gives back x. Every trick below depends on that.
XOR on bool values
Because bool is a subclass of int, ^ works on True and False. The Python docs state that for two bools, &, | and ^ "return a bool equivalent to the logical operations 'and', 'or', 'xor'."
>>> True ^ False
True
>>> True ^ True
False
>>> False ^ False
False
The same page adds that and, or and != "should be preferred over" &, | and ^ for booleans. That leads to the next section.
How to do a logical XOR in Python
Python has and, or and not, but no xor keyword. The grammar in the language reference defines only those three boolean operators. For a logical XOR, compare truth values with !=:
def exactly_one(first_condition, second_condition):
return bool(first_condition) != bool(second_condition)
>>> exactly_one(0, "text")
True
>>> exactly_one("a", "b")
False
>>> exactly_one([], None)
False
The bool() calls matter. Using ^ directly on non-bool values is bitwise, not logical. Both 1 and 2 are truthy, so a logical XOR should say "not exactly one", but 1 ^ 2 is 3, which is also truthy:
>>> 1 ^ 2
3
>>> bool(1) ^ bool(2)
False
If you need "exactly one of several conditions", count them instead: sum(map(bool, conditions)) == 1.
Toggle a flag with XOR
XOR with a bit mask flips exactly the bits that are 1 in the mask and leaves the rest alone. This is the standard way to toggle a flag stored in an integer:
FLAG_BOLD = 0b0001
FLAG_ITALIC = 0b0010
FLAG_UNDERLINE = 0b0100
style = FLAG_BOLD | FLAG_UNDERLINE # 0b0101
style ^= FLAG_ITALIC # italic on -> 0b0111
style ^= FLAG_ITALIC # italic off -> 0b0101
print(bin(style))
Example output: 0b101. Because XOR is its own inverse, running the same line twice returns the original value. If you want to turn a flag on or off rather than flip it, use |= to set and &= ~mask to clear.
Check whether two numbers are equal or differ in a bit
a ^ b is 0 exactly when a == b, and each 1 bit in the result marks a position where they differ. Counting those bits gives the Hamming distance between two integers. int.bit_count() returns the number of ones in the binary representation of the absolute value and was added in Python 3.10:
>>> (0b1011 ^ 0b1001).bit_count()
1
>>> bin(0b1011 ^ 0b1001)
'0b10'
On older versions use bin(a ^ b).count("1"), which the documentation gives as the equivalent.
Find the one number that appears once
Since x ^ x is 0 and XOR does not depend on order, XORing a whole list cancels every value that appears twice. What is left is the value that appears once:
from functools import reduce
from operator import xor
numbers = [4, 1, 2, 1, 2]
print(reduce(xor, numbers))
Example output: 4. The operator module provides xor(a, b), which the documentation defines as returning a ^ b. That makes it usable wherever a function is expected, such as reduce or map. The in-place version, operator.ixor(a, b), is equivalent to a ^= b. For integers it returns the new value rather than changing anything, so you must write a = ixor(a, b). The trick only works when every other value appears an even number of times.
Swap two variables with XOR
You will see this in interview questions:
a = 5
b = 9
a ^= b
b ^= a
a ^= b
print(a, b)
Example output: 9 5. It works, but in Python tuple assignment is clearer and just as short: a, b = b, a. Use the XOR version only to understand the idea.
XOR a message with a key (a toy cipher)
Applying the same key twice restores the original, because (x ^ k) ^ k == x. This is how a simple XOR cipher works, byte by byte:
def xor_bytes(payload, key_byte):
return bytes(byte ^ key_byte for byte in payload)
scrambled = xor_bytes(b"hi", 0x2A)
print(scrambled)
print(xor_bytes(scrambled, 0x2A))
Example output:
b'BC'
b'hi'
Iterating over bytes gives integers, so ^ applies directly. This is an illustration of the operator, not protection for real data: a single repeated key byte is trivial to break. For real secrets use a vetted cipher. On larely, the encrypt tool runs entirely in your browser.
XOR on sets: symmetric difference
For sets, ^ returns the symmetric difference. The documentation describes set ^ other as returning "a new set with elements in either the set or other but not both."
>>> {1, 2, 3} ^ {3, 4}
{1, 2, 4}
>>> {"a", "b"} ^ {"a", "b"}
set()
The method form, symmetric_difference(), accepts any iterable, while the operator form needs both sides to be sets. This is useful for comparing two lists of names or IDs and seeing everything that is in one but not the other.
Negative numbers
The docs say bitwise operations behave "as though carried out in two's complement with an infinite number of sign bits." In practice a negative number has an unbroken run of 1 bits on the left, and the result follows from that:
>>> 5 ^ -1
-6
>>> ~5
-6
XOR with -1 flips every bit, which is the same as ~. Note that bin() does not show the two's complement form: it prints a minus sign followed by the magnitude, for example bin(-37) gives '-0b100101'.
Precedence and common mistakes
The three bitwise operators sit at different priority levels. & binds tightest, then ^, then |, and all three bind more loosely than the shift operators and arithmetic but more tightly than comparisons. So 5 ^ 3 == 6 compares the XOR result, and 1 | 2 ^ 3 is parsed as 1 | (2 ^ 3):
>>> 5 ^ 3 == 6
True
>>> 1 | 2 ^ 3
1
>>> (1 | 2) ^ 3
0
When you mix operators, add parentheses. Other mistakes to watch for:
- Expecting a power.
2 ^ 3is1, not8. Exponentiation is2 ** 3. The other arithmetic operators are covered in Python operators explained. - Using it on floats.
2.5 ^ 1raisesTypeError: unsupported operand type(s) for ^: 'float' and 'int'. Convert withint()first, if truncating is acceptable. - Using it as logical XOR on non-bools. See the section above: use
bool(a) != bool(b).
Make your own class support ^
As the reference says, a custom object can take part in ^ by defining __xor__(), and __rxor__() for when it is the right-hand operand:
class Permissions:
def __init__(self, bits):
self.bits = bits
def __xor__(self, other):
if not isinstance(other, Permissions):
return NotImplemented
return Permissions(self.bits ^ other.bits)
def __repr__(self):
return f"Permissions({self.bits:#06b})"
print(Permissions(0b0110) ^ Permissions(0b0011))
Example output: Permissions(0b0101). Returning NotImplemented for unsupported types lets Python try the other operand's method and then raise the standard TypeError.
Frequently asked questions
- What is the XOR operator in Python?
- The XOR operator in Python is the caret, ^. For integers it compares the binary digits of both numbers and sets each result bit to 1 only where the two input bits differ, so 5 ^ 3 returns 6.
- How do I do a logical XOR on two conditions in Python?
- Python has no logical xor keyword. Compare the truth values with !=, as in bool(a) != bool(b). The result is True when exactly one of the two conditions is true. The Python documentation recommends != over ^ for booleans.
- Why does 1 ^ 2 return 3 and not True or False?
- Because ^ is a bitwise operator. It works on the binary digits of integers: 01 XOR 10 gives 11, which is 3. It only behaves like a logical XOR when both operands are bool values.
- Does ^ work on floats or strings in Python?
- No. Integers, bools and sets support ^ out of the box. Floats and strings raise TypeError: unsupported operand type(s) for ^. Convert to int, or to bytes and XOR byte by byte, depending on what you need.
- What is the difference between ^ and ** in Python?
- ^ is bitwise XOR, while ** is exponentiation. People coming from math notation often write 2 ^ 3 expecting 8, but Python returns 1 because it XORs 0b10 and 0b11. Use 2 ** 3 for a power.