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 | Ways to concatenate tuples
Next article icon

Python | How to Concatenate tuples to nested tuples

Last Updated : 12 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with tuples, we can have a problem in which we need to convert individual records into a nested collection yet remaining as separate element. Usual addition of tuples, generally adds the contents and hence flattens the resultant container, this is usually undesired. Let's discuss certain ways in which this problem is solved.

Method #1 : Using + operator + ", " operator during initialization In this method, we perform the usual addition of tuple elements, but while initializing tuples, we add a comma after the tuple so that they don't get flattened while addition. 

  1. Two tuples are initialized using the comma notation and assigned to variables test_tup1 and test_tup2 respectively.
  2. The original tuples are printed using the print function and string concatenation with the help of the str function to convert the tuple to a string.
  3. The tuples are concatenated using the + operator and assigned to a new variable called res.
  4. The result is printed using the print function and string concatenation with the help of the str function to convert the tuple to a string.
Python3
# Python3 code to demonstrate working of # Concatenating tuples to nested tuples # using + operator + ", " operator during initialization  # initialize tuples test_tup1 = (3, 4), test_tup2 = (5, 6),  # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2))  # Concatenating tuples to nested tuples # using + operator + ", " operator during initialization res = test_tup1 + test_tup2  # printing result print("Tuples after Concatenating : " + str(res)) 
Output : 
The original tuple 1 : ((3, 4), ) The original tuple 2 : ((5, 6), ) Tuples after Concatenating : ((3, 4), (5, 6))

Time complexity: O(1)
Auxiliary space: O(1)

Method #2 : Using ", " operator during concatenation 

This task can be performed by applying ", " operator during concatenation as well. It can perform the safe concatenation. 

  1. First, two tuples test_tup1 and test_tup2 are initialized with values (3, 4) and (5, 6) respectively.
  2. The original values of both tuples are printed using the print() function with the help of string concatenation using the + operator.
  3. The tuples are concatenated to create a nested tuple using the , operator and assigned to the variable res. Here, the + operator is used to concatenate two tuples and create a new tuple.
  4. Finally, the result is printed using the print() function and string concatenation using the + operator. The variable res contains the nested tuple created by concatenating test_tup1 and test_tup2.
Python3
# Python3 code to demonstrate working of # Concatenating tuples to nested tuples # Using ", " operator during concatenation  # initialize tuples test_tup1 = (3, 4) test_tup2 = (5, 6)  # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2))  # Concatenating tuples to nested tuples # Using ", " operator during concatenation res = ((test_tup1, ) + (test_tup2, ))  # printing result print("Tuples after Concatenating : " + str(res)) 
Output : 
The original tuple 1 : ((3, 4), ) The original tuple 2 : ((5, 6), ) Tuples after Concatenating : ((3, 4), (5, 6))

Time complexity: O(1) (constant time)
Auxiliary space: O(1) (constant space)

Method #3 : Using list(),extend() and tuple() methods

Python3
# Python3 code to demonstrate working of # Concatenating tuples to nested tuples # using + operator + ", " operator during initialization  # initialize tuples test_tup1 = (3, 4), test_tup2 = (5, 6),  # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2))  # Concatenating tuples to nested tuples test_tup1 = list(test_tup1) test_tup2 = list(test_tup2) test_tup1.extend(test_tup2) # printing result print("Tuples after Concatenating : " + str(tuple(test_tup1))) 

Output
The original tuple 1 : ((3, 4),) The original tuple 2 : ((5, 6),) Tuples after Concatenating : ((3, 4), (5, 6))

Time complexity: O(1), which means it's a constant time operation.
Auxiliary space: O(n), where n is the size of the concatenated tuple.

Method #4: Using the itertools.chain() function

The itertools.chain() function takes multiple iterables and returns a single iterator that yields all the elements from each of the iterables in sequence. By passing the two tuples as arguments to itertools.chain(), we can concatenate them into a single tuple, which can then be converted to a nested tuple using the tuple() function.

Python3
import itertools  test_tup1 = (3, 4), test_tup2 = (5, 6),  # using itertools.chain() to concatenate tuples to nested tuples res = tuple(itertools.chain(test_tup1, test_tup2))  # printing result print("Tuples after Concatenating : ", res) 

Output
Tuples after Concatenating :  ((3, 4), (5, 6))

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

Method #5: Using the reduce() method of functools

This program demonstrates how to concatenate two tuples into a nested tuple using the reduce() method from the functools module. It initializes two tuples, concatenates them using reduce(), and prints the result.

Python3
# Python3 code to demonstrate working of # Concatenating tuples to nested tuples # using functools.reduce() method  # import functools module import functools  # initialize tuples test_tup1 = (3, 4), test_tup2 = (5, 6),  # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2))  # Concatenating tuples to nested tuples # using functools.reduce() method res = functools.reduce(lambda x, y: x + y, (test_tup1, test_tup2))  # printing result print("Tuples after Concatenating : " + str(res)) 

Output
The original tuple 1 : ((3, 4),) The original tuple 2 : ((5, 6),) Tuples after Concatenating : ((3, 4), (5, 6))

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 6 : using the extend() method of the list class.

Approach:

  1. Initialize tuples test_tup1 and test_tup2 with values (3, 4) and (5, 6) respectively.
  2. Create an empty list, last.
  3. Use the extend() method to add tuples test_tup1 and test_tup2 to last.
  4. Use the tuple() constructor to convert lst into a nested tuple.
  5. Assign the nested tuple to the variable res.
  6. Print the concatenated nested tuple.
Python3
# Python3 code to demonstrate working of # Concatenating tuples to nested tuples # using extend() method of list class  # initialize tuples test_tup1 = (3, 4) test_tup2 = (5, 6)  # create an empty list lst = []  # Concatenating tuples to nested tuples # using extend() method of list class lst.extend(test_tup1) lst.extend(test_tup2) res = tuple([lst[i:i+2] for i in range(0, len(lst), 2)])  # printing result print("Tuples after Concatenating : ", res) 

Output
Tuples after Concatenating :  ([3, 4], [5, 6])

Time complexity of this method is O(n) where n is the number of elements in both tuples. 
Auxiliary space required is O(n) as we are creating a list to store the concatenated tuples.


Next Article
Python | Ways to concatenate tuples
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python tuple-programs
Practice Tags :
  • python

Similar Reads

  • Python | Convert string tuples to list tuples
    Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this tas
    4 min read
  • Python | Ways to concatenate tuples
    Many times, while working with records, we can have a problem in which we need to add two records and store them together. This requires concatenation. As tuples are immutable, this task becomes little complex. Let's discuss certain ways in which this task can be performed. Method #1 : Using + opera
    6 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
    7 min read
  • Python - Join Tuples to Integers in Tuple List
    Sometimes, while working with Python records, we can have a problem in which we need to concatenate all the elements, in order, to convert elements in tuples in List to integer. This kind of problem can have applications in many domains such as day-day and competitive programming. Let's discuss cert
    5 min read
  • Python | How to get unique elements in nested tuple
    Sometimes, while working with tuples, we can have a problem in which we have nested tuples and we need to extract elements that occur singly, i.e are elementary. This kind of problem can have applications in many domains. Let's discuss certain ways in which this problem can be solved. Method #1: Usi
    7 min read
  • Python - Concatenate Tuple to Dictionary Key
    Given Tuples, convert them to the dictionary with key being concatenated string. Input : test_list = [(("gfg", "is", "best"), 10), (("gfg", "for", "cs"), 15)] Output : {'gfg is best': 10, 'gfg for cs': 15} Explanation : Tuple strings concatenated as strings. Input : test_list = [(("gfg", "is", "best
    6 min read
  • Flatten tuple of List to tuple - Python
    The task of flattening a tuple of lists to a tuple in Python involves extracting and combining elements from multiple lists within a tuple into a single flattened tuple. For example, given tup = ([5, 6], [6, 7, 8, 9], [3]), the goal is to flatten it into (5, 6, 6, 7, 8, 9, 3). Using itertools.chain(
    3 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 thi
    10 min read
  • Python - K length Concatenate Single Valued Tuple
    Sometimes, while working with Python Tuples, we can have a problem in which we need to perform concatenation of single values tuples, to make them into groups of a bigger size. This kind of problem can occur in web development and day-day programming. Let's discuss certain ways in which this task ca
    5 min read
  • Python - Convert List of Lists to Tuple of Tuples
    Sometimes, while working with Python data, we can have a problem in which we need to perform interconversion of data types. This kind of problem can occur in domains in which we need to get data in particular formats such as Machine Learning. Let us discuss certain ways in which this task can be per
    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