What does the caret operator (^) in Python do?

It's a bitwise XOR (exclusive OR).

It results to true if one (and only one) of the operands (evaluates to) true.

To demonstrate:

>>> 0^0
0
>>> 1^1
0
>>> 1^0
1
>>> 0^1
1

To explain one of your own examples:

>>> 8^3
11

Think about it this way:

1000  # 8 (binary)
0011  # 3 (binary)
----  # APPLY XOR ('vertically')
1011  # result = 11 (binary)

It invokes the __xor__() or __rxor__() method of the object as needed, which for integer types does a bitwise exclusive-or.


It's a bit-by-bit exclusive-or. Binary bitwise operators are documented in chapter 5 of the Python Language Reference.