![]() |
VOOZH | about |
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.
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.
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
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.
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.
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:
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.