XOR operator
In Python, the XOR operator (^) compares two integers bit by bit and sets each bit of the result only where the two inputs disagree. XOR is short for exclusive or, which states the rule in words: the answer is true when one side or the other holds, but not when both do. That’s why 6 ^ 3 gives you 5. In binary, 6 is 0b110 and 3 is 0b011, which differ in the outer two positions and agree in the middle one.
Flip any bit of a or b below to watch that rule play out one column at a time, with the disagreeing positions lighting up in the result:
Because Booleans are a subclass of int, you can apply ^ to them directly, and True ^ False evaluates to True. Python has no xor keyword to go alongside and and or, so a != comparison does the same job when both operands are already Booleans.
Sets overload ^ as symmetric difference, so {1, 2, 3} ^ {3, 4} returns {1, 2, 4}. Your own classes can join in by defining the .__xor__() magic method. The augmented form ^= rebinds the name on the left to the result of the operation.
Among the bitwise operators, ^ binds more tightly than | and less tightly than &, and all three outrank comparisons. That means Python reads flags ^ mask == 0 as (flags ^ mask) == 0 rather than comparing mask against 0 first. Parenthesize when the precedence isn’t obvious at a glance.
Example
Say you’re storing file permissions as individual bits, and you need a toggle that turns the write bit on when it’s off and off when it’s on:
>>> READ, WRITE, EXECUTE = 0b100, 0b010, 0b001
>>> permissions = READ | EXECUTE
>>> bin(permissions)
'0b101'
>>> permissions ^= WRITE
>>> bin(permissions)
'0b111'
>>> permissions ^= WRITE
>>> bin(permissions)
'0b101'
Each ^= compares permissions against WRITE one position at a time. The two operands agree everywhere except the write slot, so the read and execute bits survive untouched while that single bit flips. Bitwise OR could only ever switch that bit on, so a toggle needs XOR. Applying the same operation a second time puts the value back where it started.
Related Resources
Tutorial
Bitwise Operators in Python
Learn how to use Python's bitwise operators to manipulate individual bits of data at the most granular level.
For additional information on related topics, take a look at the following resources:
- Binary, Bytes, and Bitwise Operators in Python (Course)
- Operators and Expressions in Python (Tutorial)
- Sets in Python (Tutorial)
- Operator and Function Overloading in Custom Python Classes (Tutorial)
- Using the "or" Boolean Operator in Python (Tutorial)
- Bitwise Operators in Python (Quiz)
- Python Operators and Expressions (Course)
- Operators and Expressions in Python (Quiz)
- Using Sets in Python (Course)
- Python Sets (Quiz)
- Using the Python or Operator (Course)
- Using the "or" Boolean Operator in Python (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Martin Breuss • Updated Sept. 15, 2026