xor in python (XOR operation in Python)

In Python, the ^ operator is used to execute the XOR (exclusive OR) operation. Bit by bit, two binary values are compared in this process, which yields 1 for each bit position where only one bit is 1 (i.e., they vary).

It functions as follows:

Basic XOR Operation

a = 5   # Binary: 0101
b = 3   # Binary: 0011

result = a ^ b  # Binary result: 0110, which is 6 in decimal
print(result)   # Output: 6

Explanation

The XOR operation here:

  • Compares each bit of a and b.
  • Returns 1 if the bits differ, and 0 if they are the same.

In this example:

  • (0101 \text{ XOR } 0011 = 0110) (binary), which is 6 in decimal.

XOR with Booleans

With booleans, XOR evaluates to True only if one operand is True and the other is False:

print(True ^ False)  # Output: True
print(True ^ True)   # Output: False

XOR in Python for Multiple Use Cases

  • Swapping values without a temporary variable:
  x = 10
  y = 5
  x = x ^ y
  y = x ^ y
  x = x ^ y
  print(x, y)  # Output: 5 10
  • Finding the single non-duplicate element in a list (often used in problems where each element appears twice except one):
  arr = [2, 3, 5, 3, 2]
  unique_element = 0
  for num in arr:
      unique_element ^= num
  print(unique_element)  # Output: 5

The XOR operation is efficient for tasks like finding unique elements or performing bitwise operations, as it works directly on binary data.

For example:

a = 5    # Binary: 0101
b = 3    # Binary: 0011
result = a ^ b  # Result: 0110, or 6 in decimal
print(result)   # Output: 6

In this case, 5 and 3 are compared:

  • At each position where the bits differ (one is 1 and the other 0), the XOR returns 1.
  • Where bits match, it returns 0.

The XOR operation can also be useful in applications such as finding unique elements in a list where duplicates cancel each other out or swapping two variables without a temporary variable:

# Finding a unique element in a list
nums = [2, 3, 2, 4, 3]
unique = 0
for num in nums:
    unique ^= num
print(unique)  # Output: 4

# Swapping variables without a temporary variable
x, y = 10, 20
x = x ^ y
y = x ^ y
x = x ^ y
print(x, y)  # Output: 20, 10

The XOR operator is efficient for these kinds of bitwise operations due to its simplicity and direct manipulation of binary data.


Leave a Comment