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 - Maximize Nested Tuples
Next article icon

Addition in Nested Tuples – Python

Last Updated : 06 Apr, 2023
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 addition of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let’s discuss certain ways in which this problem can be solved. 

Method #1: Using zip() + nested generator expression The combination of above functions can be used to perform the task. In this, we combine the elements across tuples using zip(). The iterations and summation logic is provided by generator expression. 

Python3




# Python3 code to demonstrate working of
# Addition in nested tuples
# 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))
 
# Addition in nested tuples
# 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 summation : " + 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 summation : ((7, 10), (7, 14), (3, 10), (8, 13))

Time complexity: O(n^2) where n is the length of the input tuples, because the program uses nested loops to iterate through the tuples.
Auxiliary Space: O(n^2), because the program creates a new tuple of the same size as the input tuples to store the result.

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
# Addition in nested tuples
# using isinstance() + zip() + loop + list comprehension
 
# function to perform task
def tup_sum(tup1, tup2):
    if isinstance(tup1, (list, tuple)) and isinstance(tup2, (list, tuple)):
       return tuple(tup_sum(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))
 
# Addition in nested tuples
# using isinstance() + zip() + loop + list comprehension
res = tuple(tup_sum(x, y) for x, y in zip(test_tup1, test_tup2))
 
# printing result
print("The resultant tuple after summation : " + 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 summation : ((7, 10), (7, 14), (3, 10), (8, 13))

Time complexity: O(n), where n is the total number of elements in the input tuples. 
Auxiliary space: O(n), where n is the total number of elements in the input tuples.

Method 3: Using numpy
Note: Install numpy module using command “pip install numpy”

This approach uses numpy to perform element-wise addition on the nested tuples. It requires numpy to be installed, then it can be done as follows:

Python3




import numpy as np
 
# Initializing the two tuples for element-wise addition
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 numpy to perform element-wise addition on the nested tuples
res = tuple(tuple(i) for i in np.add(test_tup1, test_tup2))
 
#Printing the final result
print(res)
#This code is contributed by Edula Vinay Kumar Reddy
 
 

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)) ((7, 10), (7, 14), (3, 10), (8, 13))  

Time complexity: O(n) where n is the number of elements in the nested tuple.
Auxiliary Space: O(n)

Method 4: Using map() and lambda function

Use the map() function and a lambda function to perform element-wise addition on the nested tuples.

Step-by-step approach:

  • Define a lambda function that takes two tuples as arguments and returns a tuple with element-wise addition of the two tuples.
  • Use the map() function to apply the lambda function to each pair of tuples from the two original tuples.
  • Convert the result to a tuple of tuples using the tuple() function.

Below is the implementation of the above approach:

Python3




# Initializing the two tuples for element-wise addition
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
 
# Define a lambda function for element-wise addition
add_tuple = lambda x, y: tuple(map(sum, zip(x, y)))
 
# Apply the lambda function to each pair of tuples using map()
result = tuple(map(add_tuple, test_tup1, test_tup2))
 
# Print the final result
print(result)
 
 
Output
((7, 10), (7, 14), (3, 10), (8, 13))

Time complexity: O(n), where n is the number of tuples in the original tuples. 
Auxiliary space: O(n), since we need to create a new tuple to store the result.

Method 6: Using a for loop and append()

  1. Two tuples, test_tup1 and test_tup2, are initialized with element-wise addition values.
  2. An empty list result is initialized to store the results of the element-wise addition.
  3. A for loop is set up to iterate over the length of test_tup1 using the range() function.
  4. For each iteration of the loop, sum_tuple is initialized with an expression that adds the corresponding elements of test_tup1 and test_tup2 for the current iteration.
  5. The sum_tuple is appended to the result list using the append() method.
  6. After the for loop completes, result is converted to a tuple using the tuple() function.
  7. Finally, the resulting tuple is printed using the print() function.

Python3




# Initializing the two tuples for element-wise addition
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
 
# Initialize an empty list to store the results
result = []
 
# Loop over the tuples and add the elements
for i in range(len(test_tup1)):
    sum_tuple = tuple([test_tup1[i][j] + test_tup2[i][j] for j in range(len(test_tup1[i]))])
    result.append(sum_tuple)
 
# Convert the list to a tuple and print the final result
result = tuple(result)
print(result)
 
 
Output
((7, 10), (7, 14), (3, 10), (8, 13))

Time Complexity: O(n^2) where n is the length of the tuples. The for loop has to iterate over each element in both tuples, so the time complexity is quadratic.

Auxiliary Space: O(n) where n is the length of the tuples. The append() method is used to add each element



Next Article
Python - Maximize Nested Tuples
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python tuple-programs
Practice Tags :
  • python

Similar Reads

  • Python - Pairwise Addition in Tuples
    Sometimes, while working with data, we can have a problem in which we need to find cumulative result. This can be of any type, product or summation. Here we are gonna discuss about adjacent element addition. Let’s discuss certain ways in which this task can be performed. Method #1 : Using zip() + ge
    4 min read
  • Python | Addition of tuples
    Sometimes, while working with records, we might have a common problem of adding 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 performed. Metho
    5 min read
  • Python - Flatten Nested Tuples
    Sometimes, while working with Python Tuples, we can have a problem in which we need to perform flattening of tuples, which can be nested and undesired. This can have application across many domains such as Data Science and web development. Let's discuss certain way in which this task can be performe
    7 min read
  • Python - Maximize Nested Tuples
    Sometimes, while working with records, we can have a problem in which we require to perform an index-wise maximum of tuple elements. This can get complicated with tuple elements being tuples and inner elements again being tuples. Let’s discuss certain ways in which this problem can be solved. Method
    8 min read
  • Tuple Division in Python
    Sometimes, while working with records, we can have a problem in which we may need to perform mathematical division 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 Th
    6 min read
  • Python - Iterate over Tuples in Dictionary
    In this article, we will discuss how to Iterate over Tuples in Dictionary in Python. Method 1: Using index We can get the particular tuples by using an index: Syntax: dictionary_name[index] To iterate the entire tuple values in a particular index for i in range(0, len(dictionary_name[index])): print
    2 min read
  • Python - Extend consecutive tuples
    Given list of tuples, join consecutive tuples. Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)] Output : [(3, 5, 6, 7, 3, 2, 4, 3), (3, 2, 4, 3, 9, 4), (9, 4, 2, 3, 2)] Explanation : Elements joined with their consecutive tuples. Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3)] Ou
    3 min read
  • Print a List of Tuples in Python
    The task of printing a list of tuples in Python involves displaying the elements of a list where each item is a tuple. A tuple is an ordered collection of elements enclosed in parentheses ( ), while a list is an ordered collection enclosed in square brackets [ ]. Using print()print() function is the
    2 min read
  • Python - Edit objects inside tuple
    Sometimes, while working with tuples, being immutable can offer a lot of confusion regarding its working. One of the questions that can pop into the mind is, Are objects inside tuples mutable? The answer to this is Yes. Let's discuss certain ways in which this can be achieved. Method #1: Using Acces
    5 min read
  • Python - Specific Range Addition in List
    Sometimes, while working with Python, we need to perform an edition in the Python list. And sometimes we need to perform this to a specific index range in it. This kind of application can have applications in many domains. Let us discuss certain ways in which this task can be performed.  Method #1:
    4 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