Python | Nested Tuples Subtraction
Last Updated : 25 Apr, 2025
Sometimes, while working with records, we can have a problem in which we require to perform index-wise subtraction of tuple elements. This can get complicated with tuple elements being tuples and inner elements again being tuple. Let’s discuss certain ways in which this problem can be solved.
Method #1: Using zip() + nested generator expression
The combination of the above functions can be used to perform the task. In this, we combine the elements across tuples using zip(). The iterations and difference logic are provided by the generator expression.
Python3
test_tup1 = (( 1 , 3 ), ( 4 , 5 ), ( 2 , 9 ), ( 1 , 10 ))
test_tup2 = (( 6 , 7 ), ( 3 , 9 ), ( 1 , 1 ), ( 7 , 3 ))
print ( "The original tuple 1 : " + str (test_tup1))
print ( "The original tuple 2 : " + str (test_tup2))
res = tuple ( tuple (a - b for a, b in zip (tup1, tup2))
for tup1, tup2 in zip (test_tup1, test_tup2))
print ( "The resultant tuple after subtraction : " + str (res))
|
Output : The original tuple 1 : ((1, 3), (4, 5), (2, 9), (1, 10)) The original tuple 2 : ((6, 7), (3, 9), (1, 1), (7, 3)) The resultant tuple after subtraction : ((-5, -4), (1, -4), (1, 8), (-6, 7))
Method #2: Using isinstance() + zip() + loop + list comprehension
The combination of above functions can be used to perform this particular task. In this, we check for the nesting type and perform recursion. This method can give flexibility of more than 1 level nesting.
Python3
def tup_diff(tup1, tup2):
if isinstance (tup1, ( list , tuple )) and isinstance (tup2, ( list , tuple )):
return tuple (tup_diff(x, y) for x, y in zip (tup1, tup2))
return tup1 - tup2
test_tup1 = (( 1 , 3 ), ( 4 , 5 ), ( 2 , 9 ), ( 1 , 10 ))
test_tup2 = (( 6 , 7 ), ( 3 , 9 ), ( 1 , 1 ), ( 7 , 3 ))
print ( "The original tuple 1 : " + str (test_tup1))
print ( "The original tuple 2 : " + str (test_tup2))
res = tuple (tup_diff(x, y) for x, y in zip (test_tup1, test_tup2))
print ( "The resultant tuple after subtraction : " + str (res))
|
Output : The original tuple 1 : ((1, 3), (4, 5), (2, 9), (1, 10)) The original tuple 2 : ((6, 7), (3, 9), (1, 1), (7, 3)) The resultant tuple after subtraction : ((-5, -4), (1, -4), (1, 8), (-6, 7))
Time complexity: O(n), where n is the number of elements in the tuples.
Auxiliary space: O(n), as the code creates a new tuple to store the result of the subtraction.
Approach 3: Using NumPy
Note: Install numpy module using command “pip install numpy”
Python3
import numpy as np
test_tup1 = (( 1 , 3 ), ( 4 , 5 ), ( 2 , 9 ), ( 1 , 10 ))
test_tup2 = (( 6 , 7 ), ( 3 , 9 ), ( 1 , 1 ), ( 7 , 3 ))
arr1 = np.array(test_tup1)
arr2 = np.array(test_tup2)
result = arr1 - arr2
result = tuple ( map ( tuple , result))
print (result)
|
Output:
((-5, -4), (1, -4), (1, 8), (-6, 7))
Time complexity: O(n)
Auxiliary Space: O(n)
Explanation: Here, we are using numpy to perform the subtraction of nested tuples. The NumPy library provides the numpy array which can perform the subtraction of elements between arrays. We convert the input tuples to numpy arrays and then perform a subtraction between the two arrays. Finally, we convert the result back to the tuple.
Approach #4: Using map() and lambda function
We can use the map() function along with lambda function to subtract the corresponding values of tuples from both the input tuples. We can then use the tuple() function to convert the resulting map object into a tuple.
- Initialize two tuples test_tup1 and test_tup2 with the given values.
- Print the original tuples test_tup1 and test_tup2.
- Use the zip() function to create an iterator that aggregates the elements from the two tuples test_tup1 and test_tup2.
- Use map() to apply a lambda function to each element of the iterator created by the zip() function. The lambda function subtracts the corresponding values of the tuples from both the input tuples.
- Convert the resulting map object into a tuple using the tuple() function.
- Assign the resulting tuple to a variable res.
- Print the resulting tuple res.
Python3
test_tup1 = (( 1 , 3 ), ( 4 , 5 ), ( 2 , 9 ), ( 1 , 10 ))
test_tup2 = (( 6 , 7 ), ( 3 , 9 ), ( 1 , 1 ), ( 7 , 3 ))
print ( "The original tuple 1 : " + str (test_tup1))
print ( "The original tuple 2 : " + str (test_tup2))
res = tuple ( map ( lambda x: tuple (x[ 0 ] - x[ 1 ]
for x in zip ( * x)), zip (test_tup1, test_tup2)))
print ( "The resultant tuple after subtraction : " + str (res))
|
OutputThe original tuple 1 : ((1, 3), (4, 5), (2, 9), (1, 10)) The original tuple 2 : ((6, 7), (3, 9), (1, 1), (7, 3)) The resultant tuple after subtraction : ((-5, -4), (1, -4), (1, 8), (-6, 7))
Time complexity: O(n), where n is the number of elements in the input tuples.
Auxiliary space: O(n), where n is the number of elements in the input tuples.
Approach #5: Using a loop and append function
In this approach, we can use a for loop to iterate through both tuples and subtract each element from the corresponding element in the other tuple. We can store the result in a new tuple using the append() function.
- Initialize two tuples test_tup1 and test_tup2 with nested tuples as their elements.
- Print the original tuples using the print() function and string concatenation.
- Create an empty list res to store the result of subtraction.
- Use a for loop with the range() function to iterate over the length of the tuples.
- Inside the for loop, create an empty list temp to store the result of each subtraction.
- Use another for loop to iterate over the length of the nested tuples.
- Inside the nested for loop, subtract each corresponding element of the nested tuples and append the result to the temp list.
- Convert the temp list to a tuple using the tuple() function and append it to the res list.
- Print the final result by converting the res list to a tuple using the tuple() function and using the print() function with string concatenation.
Python3
test_tup1 = (( 1 , 3 ), ( 4 , 5 ), ( 2 , 9 ), ( 1 , 10 ))
test_tup2 = (( 6 , 7 ), ( 3 , 9 ), ( 1 , 1 ), ( 7 , 3 ))
print ( "The original tuple 1 : " + str (test_tup1))
print ( "The original tuple 2 : " + str (test_tup2))
res = []
for i in range ( len (test_tup1)):
temp = []
for j in range ( len (test_tup1[i])):
temp.append(test_tup1[i][j] - test_tup2[i][j])
res.append( tuple (temp))
print ( "The resultant tuple after subtraction : " + str ( tuple (res)))
|
OutputThe original tuple 1 : ((1, 3), (4, 5), (2, 9), (1, 10)) The original tuple 2 : ((6, 7), (3, 9), (1, 1), (7, 3)) The resultant tuple after subtraction : ((-5, -4), (1, -4), (1, 8), (-6, 7))
Time complexity: O(n^2) where n is the length of the tuples since we have nested loops.
Auxiliary space: O(n) since we are storing the result in a new tuple.
Similar Reads
Python - Skew Nested Tuple Summation
Given a Tuple, nesting at 2nd position, return summation of 1st elements. Input : test_tup = (5, (6, (1, (9, None)))) Output : 21 Explanation : 9 + 6 + 5 + 1 = 21. Input : test_tup = (5, (6, (1, None))) Output : 12 Explanation : 1 + 6 + 5 = 12. Method #1: Using infinite loop In this, we perform get
6 min read
Python | How to get Subtraction of tuples
Sometimes, while working with records, we might have a common problem of subtracting the contents of one tuple with the corresponding index of other tuple. This has application in almost all the domains in which we work with tuple records. Letâs discuss certain ways in which this task can be perform
5 min read
Python | Mutual tuple subtraction in list
Sometimes, while working with data, we can have a problem in which we need to perform tuple subtraction among all the tuples in list. This can have application in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using combinations() + list comprehension This
3 min read
Python | Nth tuple index Subtraction by K
Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Letâs discuss certain ways in which K can be subtracted to Nth element of tuple in list. Method #1 : Using loop Using loops this t
6 min read
Python - Subtract K from tuples list
Sometimes, while working with data, we can have a problem in which we need to perform update operation on tuples. This can have application across many domains such as web development. Letâs discuss certain ways in which subtraction of K can be performed. Method #1 : Using list comprehension This is
4 min read
Python - Absolute Tuple Summation
Sometimes, while working with Python tuples, we can have a problem in which we need to perform the summation of absolute values of intermediate tuple elements. This kind of problem can have application in many domains such as web development. Let's discuss certain ways in which this task can be perf
6 min read
Python | Summation of tuples in list
Sometimes, while working with records, we can have a problem in which we need to find the cumulative sum of all the values that are present in tuples. This can have applications in cases in which we deal with a lot of record data. Let's discuss certain ways in which this problem can be solved. Metho
7 min read
Python - Dual Tuple Alternate summation
Given dual tuple, perform summation of alternate elements, i.e of indices alternatively. Input : test_list = [(4, 1), (5, 6), (3, 5), (7, 5)] Output : 18 Explanation : 4 + 6 + 3 + 5 = 18, Alternatively are added to sum. Input : test_list = [(4, 1), (5, 6), (3, 5)] Output : 13 Explanation : 4 + 6 + 3
8 min read
Python | Column summation of tuples
Sometimes, we encounter a problem where we deal with a complex type of matrix column summation in which we are given a tuple and we need to perform the summation of its like elements. This has a good application in Machine Learning domain. Let's discuss certain ways in which this can be done. Method
7 min read
Python - Tuple Matrix Columns Summation
Sometimes, while working with Tuple Matrix, we can have a problem in which we need to perform summation of each column of tuple matrix, at the element level. This kind of problem can have application in Data Science domains. Let's discuss certain ways in which this task can be performed. Input : tes
8 min read