Q:

Python program to perform XOR operation on tuples

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

XOR operation on Tuples

In this program, we are given two tuples. We need to create a Python program to return a tuple that contains the XOR elements.

Sample Input:
tuple1 = (4, 1, 7, 9, 3) , tuple2 = (2, 4, 6, 7, 8)

Output:
(6, 5, 1, 14, 11)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to perform the XOR operation on elements of tuples is by using generator expression with the zip() to map the elements of both tuples using the XOR operation and create a tuple with resultant values.

# Python program to perform XOR 
# operation on tuples

# Initializing and printing tuple
myTup1 = (4, 1, 7, 9, 3)
myTup2 = (2, 4, 6, 7, 8)
print("The elements of tuple 1 : " + str(myTup1))
print("The elements of tuple 2 : " + str(myTup2))

# Performing XOR operation on tuples 
res = tuple(ele1 ^ ele2 for ele1, ele2 in zip(myTup1, myTup2))
print("The elements of XOR tuple : " + str(res))

Output:

The elements of tuple 1 : (4, 1, 7, 9, 3)
The elements of tuple 2 : (2, 4, 6, 7, 8)
The elements of XOR tuple : (6, 5, 1, 14, 11)

Method 2:

Another method to solve the problem is by mapping the XOR operation of the tuple elements done using the XOR operator. Then convert the map to a tuple using the tuple() method.

# Python program to perform XOR 
# operation on tuples

import operator

# Initializing and printing tuple
myTup1 = (4, 1, 7, 9, 3)
myTup2 = (2, 4, 6, 7, 8)
print("The elements of tuple 1 : " + str(myTup1))
print("The elements of tuple 2 : " + str(myTup2))

# Performing XOR operation on tuples 
res = tuple(map(operator.xor, myTup1, myTup2))
print("The elements of XOR tuple : " + str(res))

Output:

The elements of tuple 1 : (4, 1, 7, 9, 3)
The elements of tuple 2 : (2, 4, 6, 7, 8)
The elements of XOR tuple : (6, 5, 1, 14, 11)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to convert tuple to integer... >>
<< Python program for creating N element incremental ...