Open In App

Python | How to Concatenate tuples to nested tuples

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
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.



Similar Reads

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 + operator This is the most Pythonic and recommended meth
6 min read
Python - Concatenate Maximum Tuples
Given a tuple list with string and its magnitude, the task is to write a python program to join all the strings with maximum magnitudes. Examples: Input : test_list = [("Gfg is best", 8), ("gfg is good", 7), ("for", 2), ("for all geeks", 8)]Output : "Gfg is best for all geeks" Explanation : 8 is maximum tuple element and concatenation of keys yield
8 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python | Unpacking nested tuples
Sometimes, while working with Python list of tuples, we can have a problem in which we require to unpack the packed tuples. This can have a possible application in web development. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension This task can be performed using list comprehension in which we iter
6 min read
Python | Convert nested sublist into tuples
Sometimes, while working with huge amount of data, we might have in which each point of data constitutes of several elements and needs to be processed as single unit. For this, we might sometimes, just receive a matrix and it's constituent data points are also lists, which don't make much sense and whole and might be required to be converted to tup
8 min read
Addition in Nested Tuples - Python
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 combin
6 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 #1: Using zip() + max() + nested generator expres
8 min read
Python | Nested Tuples Subtraction
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
7 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 performed. Input : test_tuple = ((4, 7), ((4, 5), ((6, 7),
7 min read
Python - Split in Nested tuples
Sometimes, while working with Python tuples, we can have a problem in which we need to perform split of elements in nested tuple, by a certain delimiter. This kind of problem can have application in different data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [(3, ('Gfg', 'best', 6)), (10, ('CS', 'good
7 min read
Practice Tags :