Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Skew Nested Tuple Summation
Next article icon

Python | Nested Tuples Subtraction

Last Updated : 25 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

# Python3 code to demonstrate working of
# Nested Tuples Subtraction
# using zip() + nested generator expression
 
# initialize tuples
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
 
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
 
# Nested Tuples Subtraction
# using zip() + nested generator expression
res = tuple(tuple(a - b for a, b in zip(tup1, tup2))
            for tup1, tup2 in zip(test_tup1, test_tup2))
 
# printing result
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

# Python3 code to demonstrate working of
# Nested Tuples Subtraction
# using isinstance() + zip() + loop + list comprehension
 
# function to perform task
 
 
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
 
 
# initialize tuples
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
 
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
 
# Nested Tuples Subtraction
# using isinstance() + zip() + loop + list comprehension
res = tuple(tup_diff(x, y) for x, y in zip(test_tup1, test_tup2))
 
# printing result
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

# Approach 1 : Using numpy
 
import numpy as np
 
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
 
# convert the tuples to numpy arrays
arr1 = np.array(test_tup1)
arr2 = np.array(test_tup2)
 
# perform the subtraction
result = arr1 - arr2
 
# convert back to tuple
result = tuple(map(tuple, result))
 
# print the result
print(result)
 
# This code is contributed by Edula Vinay Kumar Reddy
                      
                       

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.

  1. Initialize two tuples test_tup1 and test_tup2 with the given values.
  2. Print the original tuples test_tup1 and test_tup2.
  3. Use the zip() function to create an iterator that aggregates the elements from the two tuples test_tup1 and test_tup2.
  4. 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.
  5. Convert the resulting map object into a tuple using the tuple() function.
  6. Assign the resulting tuple to a variable res.
  7. Print the resulting tuple res.

Python3

# Python3 code to demonstrate working of
# Nested Tuples Subtraction
# using map() and lambda function
 
# initialize tuples
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
 
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
 
# Nested Tuples Subtraction
# using map() and lambda function
res = tuple(map(lambda x: tuple(x[0] - x[1]
                                for x in zip(*x)), zip(test_tup1, test_tup2)))
 
# printing result
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 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.

  1. Initialize two tuples test_tup1 and test_tup2 with nested tuples as their elements.
  2. Print the original tuples using the print() function and string concatenation.
  3. Create an empty list res to store the result of subtraction.
  4. Use a for loop with the range() function to iterate over the length of the tuples.
  5. Inside the for loop, create an empty list temp to store the result of each subtraction.
  6. Use another for loop to iterate over the length of the nested tuples.
  7. Inside the nested for loop, subtract each corresponding element of the nested tuples and append the result to the temp list.
  8. Convert the temp list to a tuple using the tuple() function and append it to the res list.
  9. 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

# initialize tuples
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
 
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
 
# using a loop and append function
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))
 
# printing result
print("The resultant tuple after subtraction : " + str(tuple(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^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.



Next Article
Python - Skew Nested Tuple Summation
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python tuple-programs
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences