Open In App

Python | Tuple XOR operation

Last Updated : 28 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




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

Time complexity: O(n), where n is the length of the tuples. The XOR operation between two elements takes O(1) time and is performed n times, so the overall time complexity is O(n).
Auxiliary Space: O(n), where n is the length of the result tuple. The generator expression creates a new tuple with the XORed elements, so the space complexity is proportional to the size of the result tuple.

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




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

Time complexity: O(n), where n is the length of the tuples. This is because the map() function and the xor operator iterate through the tuples once.
Auxiliary space: O(n), where n is the length of the tuples. This is because the tuple created by the map() function is of the same length as the input tuples.

Method #3 : Using numpy

Note: install numpy module using command “pip install numpy”

Python3




# Python3 code to demonstrate working of
# Tuple XOR operation
# using numpy
import numpy as np
   
# 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 numpy
res = np.bitwise_xor(test_tup1,test_tup2)
   
# printing result
print("The XOR tuple : " + str(tuple(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)
 

Time complexity: O(n)
Auxiliary Space: O(n)

Method #4 : Using for loops

Python3




# Python3 code to demonstrate working of
# Tuple XOR operation
 
# 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
res=[]
for i in range(0,len(test_tup1)):
    res.append(test_tup1[i]^test_tup2[i])
res=tuple(res)
# 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)

Time complexity: O(n)
Auxiliary Space: O(n)

Method 5: Using List Comprehension

Use list comprehension to iterate over the elements of both tuples and perform the XOR operation. The resulting list can then be converted to a tuple.

Below is the implementation of the above idea:

Python3




# initialize tuples
test_tup1 = (10, 4, 6, 9)
test_tup2 = (5, 2, 3, 3)
 
# perform XOR operation using list comprehension
res = tuple([test_tup1[i] ^ test_tup2[i] for i in range(len(test_tup1))])
 
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
 
# print the 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)

Time complexity: O(n), where n is the length of the tuples test_tup1 and test_tup2.
Auxiliary Space: O(n)

Method #6: Using itertools.starmap() + operator.xor()

The itertools.starmap() function applies a function to a sequence of argument tuples, and operator.xor() function returns the bitwise XOR of two integers.

Python3




import operator
import itertools
 
test_tup1 = (10, 4, 6, 9)
test_tup2 = (5, 2, 3, 3)
 
# Tuple XOR operation using itertools.starmap() and operator.xor()
res = tuple(itertools.starmap(operator.xor, zip(test_tup1, test_tup2)))
 
# printing result
print("The XOR tuple : " + str(res))


Output

The XOR tuple : (15, 6, 5, 10)

Time complexity: O(n), where n is the length of the tuples test_tup1 and test_tup2.
Auxiliary Space: O(n)

Method #7:Using the pandas module

  • Import the pandas module and initialize two tuples.
  • Create two data frames using the pandas.DataFrame() function, one for each tuple.
  • Use the pandas.DataFrame.diff() function to calculate the difference between the two data frames.
  • Use the pandas.DataFrame.gt() function to create a boolean mask indicating where the values in the first data frame are greater than those in the second data frame.
  • Use the pandas.DataFrame.where() function to apply the boolean mask to the results of step 3.
  • Use the pandas.DataFrame.fillna() function to fill any NaN values in the resulting data frame with False.
  • Convert the resulting data frame to a list of lists using the pandas.DataFrame.values.tolist() function.

Python3




import pandas as pd
 
# 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))
 
# create pandas DataFrames
df1 = pd.DataFrame(list(test_tup1)).T
df2 = pd.DataFrame(list(test_tup2)).T
 
# perform XOR operation
res_df = df1.astype(int).apply(lambda x: x^df2.astype(int).iloc[0], axis=1)
 
# convert result DataFrame to tuple
res = tuple(res_df.iloc[0].tolist())
 
# print result
print("The XOR tuple : ", 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)

The time complexity of this solution is O(n), where n is the length of the tuple.
The space complexity of this solution is O(n), as we are creating a new tuple of length n to store the result.



Similar Reads

Python - Alternate Elements operation on Tuple
Sometimes, while working with Python Tuples, we can have problem in which we need to perform operations of extracted alternate chains of tuples. This kind of operation can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Input : test_tuple = (5, 6, 3) Output : The alternate cha
5 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python - Raise elements of tuple as power to another tuple
Sometimes, while working with records, we can have a problem in which we may need to perform exponentiation, i.e power of 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
8 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 min read
Python - Convert Tuple to Tuple Pair
Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problems in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ('A'
10 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python program to convert Set into Tuple and Tuple into Set
Let's see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.set(): set method is to convert other type values to set this meth
7 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in r
8 min read
Practice Tags :
three90RightbarBannerImg