What does the caret (^) operator do?

It’s a bitwise XOR (exclusive OR).

It evaluates to True if and only if its arguments differ (one is True, the other is False).

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)

Leave a Comment