Explain Codes LogoExplain Codes Logo

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

python
xor
boolean
functions
Alex KataevbyAlex Kataev·Aug 15, 2024
TLDR

Perform XOR in Python with the ^ operator for integers, and != operator for booleans:

# Boolean XOR a, b = True, False print(a != b) # Prints True - Why? Only one of them partying, bro! # Integer Bitwise XOR print(5 ^ 3) # Prints 6 - Cool, right? Only the cool bits stand out!

The XOR behavior is elegantly captured by a != b for booleans and 5 ^ 3 for integers.

Handling non-boolean data types

When your variables are not native booleans, conversion to boolean values is essential. This guards against confusing results, especially when dealing with string values.

Get truthy with strings

If your variables are strings, use bool() to dodge any unexpected character vs logical comparison results.

str1, str2 = "Python", "" logical_xor = bool(str1) != bool(str2) print(logical_xor) # Prints True. One's full of life, the other's a void.

Explicit XOR logic

To map out the exact pattern of XOR, go for this explicit alternative:

explicit_xor = (a and not b) or (not a and b) print(explicit_xor) # Prints True if they're not twinning.

Reusable XOR function

For frequent XOR checks, especially with strings, shape a function for ready reapplication:

def logical_xor(str1, str2): return bool(str1) != bool(str2) # Usage example print(logical_xor("Hello", "")) # Prints True. One speaks out, the other's silent.

Going Beyond: XOR Advanced Concepts

Take a deeper dive into XOR complexities and useful workarounds for effective Python coding.

XOR under the hood

XOR fundamentals impart an understanding that can lead to innovative applications. For example, use Python's implicit type conversion between bool and int for simplifying xor operations.

The built-in XOR

Use Python's operator module to tap into a built-in bitwise XOR method. This approach becomes handy when running XOR between booleans:

from operator import xor print(xor(True, False)) # Prints True. One's up, one's down. Party on!

Multiple XOR checks

When you need to perform multiple XOR checks, here's a clever pattern that evaluates if only one variable is truthy:

bool(a) + bool(b) == 1 # One's hot, other's not. The XOR DJ spins on!

Potential TypeError landmine

Performing xor on unlike types may trip a TypeError. Always ensure your bitwise operations happen on booleans to avoid such party spoilers.

A special thanks

Here's to Nick Coghlan, a Python core developer who brilliantly revealed the secret compatibility of xor in Python banked on the subclassing of bool from int. Who knew!