^

Exclusive OR: bits that differ. And the #1 caret fact: 2 ^ 10 is 8, not 1024.

Bitwise operatorPython 1.0+Live demo
Common call
toggled = flags ^ MASK
Returns
int with only the differing bits; set symmetric difference
Replaces
x ^ x == 0 and x ^ 0 == x — the self-canceling property
Watch out
exponentiation is ** — the caret is a false friend
aaLeft operand.type: int | set · required ^ bbRight operand.type: int | set · required
int | set

Demo

Live evaluation
Try:
Inputs
aintleft operand
bintright operand
Output
2 ^ 10
8

The first case is the trap: 2 ^ 10 is 8 (0b0010 XOR 0b1010 = 0b1000) — anyone expecting 1024 wants 2 ** 10. XOR of a value with itself is always 0.

Operands

NameTypeRequiredDescription
aint | setyesLeft operand.
bint | setyesRight operand.

Return value

int | setInts: a bit is set where the operands DIFFER. Sets: the symmetric difference.

Common patterns

Toggling flags
XOR with a mask flips exactly those bits.
state ^= BLINK_BIT   # on↔off each call
Symmetric set difference
Elements in exactly one of the two sets.
changed = before ^ after

Examples

1. NOT exponentiation
2 ^ 10
Returns
8
2. Differing bits
12 ^ 10
Returns
6
3. Self-cancel
7 ^ 7
Returns
0
4. Symmetric difference
{1, 2} ^ {2, 3}
Returns
{1, 3}

Pitfalls

1. The exponentiation false friend
Coming from math notation or Excel, ^ silently computes the wrong thing.
Silent wrong answer
10 ^ 2   # "ten squared"?
8
Fix
10 ** 2
100
2. XOR swap is a party trick, not a practice
Python has tuple assignment — use it.
Obscure
a ^= b; b ^= a; a ^= b
works for ints only, unreadable
Pythonic
a, b = b, a
any types, clear

When to use

Use it
  • Toggling bits with a mask
  • Parity / checksum arithmetic
  • Symmetric difference of sets
Reach for something else
  • Powers → **
  • Simple boolean != of two bools → != reads clearer

Notes

Complexity
O(bits)
Return
new value; operands untouched
CPython impl
Objects/longobject.c :: long_xor → __xor__
Memory
No allocation for small ints
Thread-safe
Yes — pure computation

FAQ

It is associative, commutative, and self-inverse (x ^ x = 0), so XOR-ing a stream detects any single-bit flip and can reconstruct one missing value — the basis of RAID parity.

History

1.0
Core operator from the beginning.