Home » Programming » Python » Python Xor Exclusive Or

XOR (Exclusive Or) in Python

This article explains XOR (Exclusive Or) – what it is, why it’s used, and how to implement it in the Python programming language.

What is XOR / Exclusive OR

XOR – Exclusive Or – is a logical operation commonly used in computer programming.

Logically, an XOR condition is true only if the supplied arguments differ.

XOR compares two inputs and outputs, true or false, only if they are different. Those inputs are usually true/false boolean values or the result of a logical operation that returns a boolean value.

For example, XOR on two values – 1 and 1 is false – they do not differ.

XOR on two values – 0 and 1 is true, as they differ.

Uses for XOR

XOR is widely used in cryptography and when comparing data.

Checksums are used to verify data integrity – the data generated and the comparison use XOR operations to do this. There’s a really good breakdown of how this is done here, but it’s beyond the scope of this article.

More generally, you’ll find yourself using XOR in many logical comparison operations – you may have used it already and just not known that it has a name.

XOR in Python

Implementing XOR in Python is easy – get the boolean value of two variables or values and compare them for inequality – if they are not equal, the statement will return true.

This is an XOR statement in Python:

bool(value1) != bool(value2)

Super simple. The result from other logical operations can also be used:

(value1 == 3) != (value2 == 3)

Above, two variables (value1 and value2) are compared separately to see if they are equal to 3, and the XOR is calculated. If one value is equal to 3 and the other is not, the XOR will return true. If both are equal to 3 or neither is, the XOR will return false.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment