What does ^ do in python?

Question:

I’ve stumbled upon ^ operator in python, and I don’t understand what is does.
I couldn’t find anything about it online.

Asked By: ColorfulYoshi

||

Answers:

The ^ operator in Python is known as the bitwise XOR operator.
It performs a binary XOR operation on two operands and returns the result.

Let’s say you have two integers a and b, and you want to perform the XOR operation between them. The XOR operation returns 1 if the corresponding bits in the two integers are different, and 0 if they are the same.

a ^ b = 6 ^ 3 = 5

a = 110
b = 011
---------
    101 = 5
Answered By: Domen

Just like most operators, it does whatever the operands say it does (via their __xor__ method). For example:

class C:
    def __xor__(self, other):
        return 'whatever you want'

print(C() ^ C())

Output:

whatever you want

Try it online!

Answered By: Kelly Bundy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.