Python | XOR tuple operation

Python Methods and Functions

Method # 1: Using zip () + Expression Generator
A combination of the above functions can be used to accomplish this task. In this we are doing the XOR task using a generator expression and the display index of each tuple is done by zip ().

# Python3 code to demonstrate how it works
# Tuple XOR operation
# using zip () + expression generator

 
# initialize tuples

test_tup1 = ( 10 , 4 , 6 , 9

test_tup2 = ( 5 , 2 , 3 , 3

 
# print original tuples

print ( "The original tuple 1:" + str (test_tup1)) 

print ( "The original tuple 2:" + str (test_tup2)) 

 
# Tuple XOR operation
# using zip () + expression generator

res = tuple (ele1 ^ ele2 for ele1, ele2 in zip (test_tup1, test_tup2)) 

  
# print 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
A combination of the above functions can also do this task. In this we are doing the task of extending the XOR logic with xor and the mapping is done by map ().

# Python3 code to demonstrate how it works
# 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 the map () + xor

res = tuple ( map (xor, test_tup1, test_tup2)) 

 
# print 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) 




Get Solution for free from DataCamp guru