XOR of Two Variables in Python
Last Updated :
13 Aug, 2024
The XOR or exclusive is a Boolean logic operation widely used in cryptography and generating parity bits for error checking and fault tolerance. The operation takes in two inputs and produces a single output. The operation is bitwise traditionally but could be performed logically as well. This article will teach you how to get the logical XOR of two variables in Python.
XOR of Two Numbers
As XOR is a bitwise operator, it will compare bits of both integers bit by bit after converting them into binary numbers. The truth table for XOR (binary) is shown below:
The formula for XOR operation is:
XOR(A, B) = ( A .\overline{B}) + (B.\overline{A})
Performing the XOR of two integers is trivial in Python, as the language offers an operator, especially for this purpose, namely a caret ^. But this operation can also be achieved by using the operator module in Python.
Note: A few things to remember while performing the xor operation:
- The XOR should only be between homogeneous elements, i.e., their datatype should be the same.
- The bool of a string will result in True if the string is non-empty and False if the string is empty.
Now let us see the XOR operation on different datatypes in Python.
XOR on Integers
The integer numbers are first converted into the binary numbers and then each bit is compared with one another. The final answer is then again converted back into the original integer form. The following code demonstrates the usage of a caret for performing the XOR of two integer variables.
Example: Firstly two variables were initialized containing 10 and 27 integer values. Then the xor of the two variables is obtained using the caret operator. The result of the operation is displayed.
Python
# First integer
a = 10
# Second integer
b = 27
# Performing the xor and storing the result in separate variable
xor = a ^ b
print(xor)
Output:
17
Time complexity: O(1)
Space complexity: O(1)
XOR on Boolean
The XOR of two boolean variables is quite simple. The output of the XOR operation is either 0 or 1 which represents True or Flase respectively in boolean format. Hence, to get the logical XOR of boolean datatype, either True or False is provided as the input values.
Example: Firstly two boolean variables were initialized with a value and then the XOR operation is performed on them using the caret operator.
Python
# First boolean
a = True
# Second boolean
b = False
# Performing the xor operation
xor = a ^ b
print(xor)
Output:
True
Time complexity: O(1)
Space complexity: O(1)
XOR on String
Since strings are a sequence, the datatype needs to be normalized for the operation to be performed on them. Therefore, the strings would be converted to bool, and then the xor operation could be performed on them. But due to this, the result of the operation would be binary, i.e., it would result in either True or False (unlike xor of integers where resultant value is produced).
Example: Firstly two strings are defined. One of them is an empty string. Then the strings are converted to the boolean datatype, and the xor operation is performed on them. The result is displayed.
Python
# First string
a = "Hello World!"
# Second string
b = ""
# Performing the xor operation
xor = bool(a) ^ bool(b)
print(xor)
Output:
True
Time complexity: O(n)
Space complexity: O(n), where n is length of string
XOR of Two Variables using Operator Module
Python has an operator module, which provides a set of predefined functions for arithmetic, logical, bitwise and comparison operators. It also provides the XOR function of the bitwise operator which can be used to get the XOR of two variables.
Example: Firstly import the operator module. Then two variables are initialized with a value and then the XOR operation is performed on them using the operator modules’s xor function.
Python
# import module
import operator
# First integer
a = 10
# Second integer
b = 27
# Performing the xor using operator module
xor = operator.xor(a,b)
print(xor)
Output:
17
Time complexity: O(1)
Space complexity: O(1)
Swapping Two Integers using XOR without Temporary Variable
The XOR bitwise operation in Python can also be used to swap two integers without using the temporary variable. Let us see how this works.
a = a ^ b
b = a ^ b
a = a ^ b
Swapping requires three expressions with the XOR operation.
- XOR the two integers ‘a’ and ‘b’ and store its result in the integer ‘a’ itself.
- Now XOR the updated value of ‘a’ with ‘b’. This will result in the original value of ‘a’, which is now stored in ‘b’.
- Lastly, XOR ‘a’ with the now updated value of ‘b’ in previous step. The result will be the original value of ‘b’. which is now stored in ‘a’.
Example: Firstly two integers are initialized. Then using the above three steps, the swapping of two integers is done using the XOR caret operator. Finally, print the swapped integers.
Python
# First integer
a = 10
# Second integer
b = 27
print("Before Swapping:")
print("a =", a)
print("b =", b)
# swapping integers using XOR
a = a ^ b
b = a ^ b
a = a ^ b
print("After Swapping:")
print("a =", a)
print("b =", b)
Output:
Before Swapping:
a = 10
b = 27
After Swapping:
a = 27
b = 10
Similar Reads
How to use Variables in Python3?
Variable is a name for a location in memory. It can be used to hold a value and reference that stored value within a computer program. the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to the variables, you can store
3 min read
Python Variables
In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
7 min read
Assign Function to a Variable in Python
In Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability. Example: [GFGTABS] Python # defining a function de
4 min read
How to check if a Python variable exists?
Variables in Python can be defined locally or globally. There are two types of variables first one is a local variable that is defined inside the function and the second one are global variable that is defined outside the function. Method 1: Checking the existence of a local variableTo check the exi
3 min read
How To Print A Variable's Name In Python
In Python, printing a variable's name can be a useful debugging technique or a way to enhance code readability. While the language itself does not provide a built-in method to directly obtain a variable's name, there are several creative ways to achieve this. In this article, we'll explore five simp
3 min read
Unused variable in for loop in Python
Prerequisite: Python For loops The for loop has a loop variable that controls the iteration. Not all the loops utilize the loop variable inside the process carried out in the loop. Example: C/C++ Code # i,j - loop variable # loop-1 print("Using the loop variable inside :") # used loop vari
3 min read
XOR of two Binary Strings
Given two binary strings A and B of equal lengths, the task is to print a string that is the XOR of Binary Strings A and B. Examples: Input: A = "0001", B = "0010" Output: 0011 Input: A = "1010", B = "0101" Output: 1111 Approach: The idea is to iterate over both the string character by character and
7 min read
How to import variables from another file in Python?
To import variables from another file in Python, you need to use the import statement. By importing a file, you gain access to its variables and functions. This can be done by simply using import filename or from filename import variable_name to access the required variables or functions in your cur
4 min read
Python | Pandas Series.xs
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas series is a One-dimensional ndarray with axis labels. The labels need not be un
2 min read
numpy.var() in Python
numpy.var(arr, axis = None) : Compute the variance of the given data (array elements) along the specified axis(if any). Example : x = 1 1 1 1 1 Standard Deviation = 0 . Variance = 0 y = 9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4 Step 1 : Mean of distribution 4 = 7 Step 2 : Summat
3 min read