Perform XOR on two lists in Python
In this tutorial, we get to know about XOR operation and perform it on two lists in the Python program. XOR stands for “exclusive or”.That is to say, the resulting bit evaluates to “1” if only exactly one of the bits is set.
This is its Truth Table:
x | y | x ^ y ---|---|------ 0 | 0 | 0 0 | 1 | 1 1 | 0 | 1 1 | 1 | 0
This operation is performed between two corresponding bits of any number.
Example: 23 ^ 25 = 14
In Binary: 10111 ^ 11001 = 01110
10111 ^ 11001 ======= 01110 = 14
Python program to perform XOR on two lists
Here two lists are containing integer elements to perform Bitwise XOR. Using the zip module to use simultaneous value each from the list. All elements are in Decimal and output is also in Decimal.
” ^ ” is using for ‘exclusive or’ in python.
SYNTAX: >>> a ^ b
Implementation in python:
list1 = [3,4,5,6,7] # values are in decimal list2 = [10,4,2,9,23] # values are in decimal result = list(a^b for a,b in zip(list1,list2)) print('XOR =',result)
OUTPUT:
XOR = [9, 0, 7, 15, 16] # in decimal
To change the values from Binary to Decimal and vice versa
Binary to Decimal
>>> Binary = '1010' >>> int(Binary,2) # return decimal value OUTPUT: 10
Decimal to Binary
>>> x = 10 >>> Bin(x) # return binary value OUTPUT: 0b1010 # for removing '0b' from starting >>> x = 10 >>> "{0:b}".format(int(x)) OUTPUT: 1010
Thanks for visiting codespeedy. I hope it helps you.
Also read:
Leave a Reply