Open In App

Python – Flatten tuple of List to tuple

Improve
Improve
Like Article
Like
Save
Share
Report

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. 

  1. First, a tuple named test_tuple is initialized with three sub-lists of varying lengths.
  2. The original tuple is printed using the print() function and the str() method to convert the tuple to a string.
  3. 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.
  4. The tuple() function is used to convert the flattened list into a tuple.
  5. The flattened tuple is printed using the print() function and the str() method to convert the tuple to a string.

Python3




# Python3 code to demonstrate working of
# Flatten tuple of List to tuple
# Using sum() + tuple()
 
# initializing tuple
test_tuple = ([5, 6], [6, 7, 8, 9], [3])
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Flatten tuple of List to tuple
# Using sum() + tuple()
res = tuple(sum(test_tuple, []))
 
# printing result
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




# Python3 code to demonstrate working of
# Flatten tuple of List to tuple
# Using tuple() + chain.from_iterable()
from itertools import chain
 
# initializing tuple
test_tuple = ([5, 6], [6, 7, 8, 9], [3])
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Flatten tuple of List to tuple
# Using tuple() + chain.from_iterable()
res = tuple(chain.from_iterable(test_tuple))
 
# printing result
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




# Python3 code to demonstrate working of
# Flatten tuple of List to tuple
# initializing tuple
test_tuple = ([5, 6], [6, 7, 8, 9], [3])
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Flatten tuple of List to tuple
res=[]
for i in test_tuple:
    res.extend(i)
res=tuple(res)
# printing result
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




# Python3 code to demonstrate working of
# Flatten tuple of List to tuple
# initializing tuple
test_tuple = ([5, 6], [6, 7, 8, 9], [3])
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Flatten tuple of List to tuple
res = []
for i in test_tuple:
    for j in i:
        res.append(j)
res = tuple(res)
# printing result
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




# initializing tuple
test_tuple = ([5, 6], [6, 7, 8, 9], [3])
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Flatten tuple of List to tuple
# Using list comprehension and extend()
res_list = []
[res_list.extend(sublist) for sublist in test_tuple]
res = tuple(res_list)
 
# printing result
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
 
# initializing tuple
test_tuple = ([5, 6], [6, 7, 8, 9], [3])
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Flatten tuple of List to tuple
# Using itertools.chain() method
res = tuple(itertools.chain(*test_tuple))
 
# printing result
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:

  1. Define a function called flatten_tuple that takes a tuple as an argument.
  2. Check if the tuple is empty. If it is, return an empty tuple.
  3. 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.
  4. 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.
  5. Return the flattened tuple.

Python3




# Python3 code to demonstrate working of
# Flatten tuple of List to tuple
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:])
 
# initializing tuple
 
test_tuple = ([5, 6], [6, 7, 8, 9], [3])
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Flatten tuple of List to tuple
res = flatten_tuple(test_tuple)
# printing result
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.



Last Updated : 30 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads