Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let’s discuss certain ways in which this task can be performed.
Input : test_tuple = ([5], [6], [3], [8])
Output : (5, 6, 3, 8)
Input : test_tuple = ([5, 7, 8])
Output : (5, 7, 8)
Method #1: Using sum() + tuple() The combination of above functions can be used to solve this problem. In this, we perform the task of flattening using sum(), passing empty list as its argument.
- First, a tuple named test_tuple is initialized with three sub-lists of varying lengths.
- The original tuple is printed using the print() function and the str() method to convert the tuple to a string.
- The sum() function is used along with the empty list [] to flatten the tuple of lists. The sum() function works by concatenating the lists inside the tuple into a single list, which is then assigned to a variable named res.
- The tuple() function is used to convert the flattened list into a tuple.
- The flattened tuple is printed using the print() function and the str() method to convert the tuple to a string.
Python3
test_tuple = ([ 5 , 6 ], [ 6 , 7 , 8 , 9 ], [ 3 ])
print ( "The original tuple : " + str (test_tuple))
res = tuple ( sum (test_tuple, []))
print ( "The flattened tuple : " + str (res))
|
Output
The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)
Time complexity: O(n), where n is the total number of elements in all the lists of the tuple, because it has to traverse the lists in the tuple once to sum them up.
Auxiliary space: O(n), because it needs to store all the elements in a new tuple.
Method #2 : Using tuple() + chain.from_iterable() The combination of above functions can be used to solve this problem. In this, we perform task of flattening using from_iterable() and conversion to tuple using tuple().
Python3
from itertools import chain
test_tuple = ([ 5 , 6 ], [ 6 , 7 , 8 , 9 ], [ 3 ])
print ( "The original tuple : " + str (test_tuple))
res = tuple (chain.from_iterable(test_tuple))
print ( "The flattened tuple : " + str (res))
|
Output
The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)
Time Complexity: O(n), where n is the total number of elements in all the lists in the tuple.
Auxiliary Space: O(n), as the memory space required to store the result is equal to the number of elements in the flattened tuple.
Method #3: Using extend() and tuple() methods
Python3
test_tuple = ([ 5 , 6 ], [ 6 , 7 , 8 , 9 ], [ 3 ])
print ( "The original tuple : " + str (test_tuple))
res = []
for i in test_tuple:
res.extend(i)
res = tuple (res)
print ( "The flattened tuple : " + str (res))
|
Output
The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)
Time complexity: O(n), where n is the number of elements in the input tuple.
Auxiliary space: O(n), as we are using an extra list to store the flattened tuple.
Method #4: Using Nested loops
Step-by-step approach:
- Define a tuple test_tuple containing multiple lists as its elements.
- Print the original tuple test_tuple.
- Initialize an empty list res.
- Using nested for loops, iterate through each element of test_tuple and each element of the inner list.
- Append each element of the inner list to the res list.
- Convert the res list to a tuple and store it in the res variable.
- Print the flattened tuple res.
Below is the implementation of the above approach:
Python3
test_tuple = ([ 5 , 6 ], [ 6 , 7 , 8 , 9 ], [ 3 ])
print ( "The original tuple : " + str (test_tuple))
res = []
for i in test_tuple:
for j in i:
res.append(j)
res = tuple (res)
print ( "The flattened tuple : " + str (res))
|
Output
The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)
Time Complexity: O(n*n)
Auxiliary Space: O(n)
Method 5: Using list comprehension and extend()
Loop through each sublist in the test_tuple using a list comprehension. For each sublist, we extend the res_list with its elements using the extend() method. Finally, convert the res_list to a tuple using the tuple() function.
Python3
test_tuple = ([ 5 , 6 ], [ 6 , 7 , 8 , 9 ], [ 3 ])
print ( "The original tuple : " + str (test_tuple))
res_list = []
[res_list.extend(sublist) for sublist in test_tuple]
res = tuple (res_list)
print ( "The flattened tuple : " + str (res))
|
Output
The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)
Time Complexity: O(n*n)
Auxiliary Space: O(n)
Method 6: using the itertools.chain()
Use the itertools.chain() method to concatenate the sublists into a single iterable, which is then converted into a tuple using the tuple() constructor. The * operator is used to unpack the elements of the original tuple into the itertools.chain() method.
Python3
import itertools
test_tuple = ([ 5 , 6 ], [ 6 , 7 , 8 , 9 ], [ 3 ])
print ( "The original tuple : " + str (test_tuple))
res = tuple (itertools.chain( * test_tuple))
print ( "The flattened tuple : " + str (res))
|
Output
The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)
Time complexity: O(n), where n is the total number of elements in all the sublists of the original tuple. This is because we need to iterate through each element once to concatenate them into a single iterable.
Auxiliary space: O(n), where n is the total number of elements in all the sublists of the original tuple.
Method 7: Using Recursive method.
Algorithm:
- Define a function called flatten_tuple that takes a tuple as an argument.
- Check if the tuple is empty. If it is, return an empty tuple.
- Check if the first element of the tuple is a list. If it is, recursively call the function on that list and concatenate the result with the flattened rest of the tuple using the + operator.
- If the first element is not a list, add it to a new tuple with a comma, and recursively call the function on the rest of the tuple.
- Return the flattened tuple.
Python3
def flatten_tuple(tup):
if not tup:
return ()
elif isinstance (tup[ 0 ], list ):
return flatten_tuple(tup[ 0 ]) + flatten_tuple(tup[ 1 :])
else :
return (tup[ 0 ],) + flatten_tuple(tup[ 1 :])
test_tuple = ([ 5 , 6 ], [ 6 , 7 , 8 , 9 ], [ 3 ])
print ( "The original tuple : " + str (test_tuple))
res = flatten_tuple(test_tuple)
print ( "The flattened tuple : " + str (res))
|
Output
The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)
Time complexity: O(n), where n is the total number of elements in the input tuple. This is because the function iterates through each element of the tuple exactly once.
Space complexity: O(n), where n is the total number of elements in the input tuple. This is because the function creates a new tuple to store the flattened elements, which can have up to n elements. Additionally, the function uses the call stack to handle recursive calls, which can have up to n levels of recursion.
Please Login to comment...