Function of Operator in Python



In Python, the XOR operator is one of the bitwise operators and is represented by the caret symbol ^. It returns 0 if both operands are the same and 1 if the operands are different.

Truth Table of XOR

The following is the truth table of the XOR (exclusive OR) operator -

A B A^B
0 0 0
0 1 1
1 0 1
1 1 0

XOR Operation Between Integers

When we perform the XOR operation on two integers, they are first converted to their binary representations, and then the XOR operation is performed bit by bit.

Example

In the following example, we perform the XOR operation between 5 and 7, i.e., 5 ^ 7. The XOR operation is performed bit by bit on their binary representations -

  • 5 → 101
  • 7 → 111
  • 5 ^ 7 → 0102

Bit by bit operation -

  • 1 ^ 1 = 0
  • 0 ^ 1 = 1
  • 1 ^ 1 = 0

So, the result in binary is 010, which is 2 in decimal.

Open Compiler
a=5 b=7 print("Binary representation of 5:",bin(a)) #binary representation of 5 print("Binary representation of 7:",bin(7)) #binary representation of 7 result =a ^ b print("XOR Operation of 5 ^ 7:",result)

Following is the output of the above code -

Binary representation of 5: 0b101
Binary representation of 7: 0b111
XOR Operation of 5 ^ 7: 2

XOR operation on Boolean values

The boolean values True and False are considered as 1 and 0, respectively, when the XOR operation is performed. The result is True if the output is 1, and the result is False if the output is 0.

Example

Here, we have performed the XOR operation on Boolean values -

Open Compiler
a=True b=False print("XOR operation on True^True:",a ^ a) print("XOR operation on False^True:",b ^ a) print("XOR operation on True^False:",a ^ b) print("XOR operation on False^False:",b ^ b)

Following is the output of the above code -

XOR operation on True^True: False
XOR operation on False^True: True
XOR operation on True^False: True
XOR operation on False^False: False

Swapping Integers Using XOR

Using the XOR operation, we can swap two integers without using a third variable.

Example

In the following example, we have swapped the integers 5, 46 -

Open Compiler
a=5 b=46 print("Values of a,b-",a,b) a=a^b b=a^b a=a^b print("Swapped Values of a,b-",a,b)

Following is the output of the above code -

Values of a, b - 5 46
Swapped Values of a, b - 46 5
Updated on: 2025-04-18T21:45:21+05:30

165 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements