Skip to content

How do you get the logical xor of two variables in Python? โ€‹

You can use the ^ operator to get the XOR of two variables in Python. It performs a bitwise XOR on integers and a logical XOR on boolean values. Here is an example:

Get the XOR of two variables in Python

python
a = 5
b = 3
result = a ^ b
print(result)  # Bitwise XOR: 6

x = True
y = False
print(x ^ y)   # Logical XOR: True

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

For boolean values, ^ evaluates to True only when the operands differ, matching the standard logical XOR truth table.

Do you find this helpful?

Dual-run preview โ€” compare with live Symfony routes.