# Python | Tuple XOR operation

Sometimes, while working with records, we can have a problem in which we may need to perform mathematical bitwise XOR operation across tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using zip() + generator expression
The combination of above functions can be used to perform this task. In this, we perform the task of XOR using generator expression and mapping index of each tuple is done by zip().

 # Python3 code to demonstrate working of  # Tuple XOR operation # using zip() + generator expression     # initialize tuples  test_tup1 = (10, 4, 6, 9)  test_tup2 = (5, 2, 3, 3)     # printing original tuples  print("The original tuple 1 : " + str(test_tup1))  print("The original tuple 2 : " + str(test_tup2))     # Tuple XOR operation # using zip() + generator expression  res = tuple(ele1 ^ ele2 for ele1, ele2 in zip(test_tup1, test_tup2))     # printing result  print("The XOR tuple : " + str(res))

Output :

The original tuple 1 : (10, 4, 6, 9)
The original tuple 2 : (5, 2, 3, 3)
The XOR tuple : (15, 6, 5, 10)

Method #2 : Using map() + xor
The combination of above functionalities can also perform this task. In this, we perform the task of extending logic of XOR using xor and mapping is done by map().

 # Python3 code to demonstrate working of  # Tuple XOR operation  # using map() + xor from operator import xor    # initialize tuples  test_tup1 = (10, 4, 6, 9)  test_tup2 = (5, 2, 3, 3)     # printing original tuples  print("The original tuple 1 : " + str(test_tup1))  print("The original tuple 2 : " + str(test_tup2))     # Tuple XOR operation  # using map() + xor res = tuple(map(xor, test_tup1, test_tup2))     # printing result  print("The XOR tuple : " + str(res))

Output :

The original tuple 1 : (10, 4, 6, 9)
The original tuple 2 : (5, 2, 3, 3)
The XOR tuple : (15, 6, 5, 10)

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.