Search code examples
pythonoperatorscaret

What does the caret (^) operator do?


I ran across the caret operator in python today and trying it out, I got the following output:

>>> 8^3
11
>>> 8^4
12
>>> 8^1
9
>>> 8^0
8
>>> 7^1
6
>>> 7^2
5
>>> 7^7
0
>>> 7^8
15
>>> 9^1
8
>>> 16^1
17
>>> 15^1
14
>>>

It seems to be based on 8, so I'm guessing some sort of byte operation? I can't seem to find much about this searching sites other than it behaves oddly for floats, does anybody have a link to what this operator does or can you explain it here?


Solution

  • 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)