Open In App

Python – Flatten tuple of List to tuple

Last Updated : 30 Mar, 2023
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.



Similar Reads

Python program to Flatten Nested List to Tuple List
Given a list of tuples with each tuple wrapped around multiple lists, our task is to write a Python program to flatten the container to a list of tuples. Input : test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]Output : [(4, 6), (7, 4), (10, 3)]Explanation : The surrounded lists are omitted around each tuple. Input : test_list = [[[(4, 6)]],
7 min read
Python | Sort Flatten list of list
The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let's discuss certain ways in which this can be done. Method #1 : Using sorted() + list comprehension This idea is similar to flattening a list of list but in addition to it, we add a sorted
7 min read
Python | Ways to flatten a 2D list
Given a 2D list, Write a Python program to convert the given list into a flattened list. Method #1: Using chain.iterable() C/C++ Code # Python code to demonstrate # converting 2d list into 1d list # using chain.from_iterables # import chain from itertools import chain ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial list print (
5 min read
Python | Flatten given list of dictionaries
Given a list of the dictionaries, the task is to convert it into single dictionary i.e flattening a list of dictionaries. Given below are a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # to flatten list of dictionaries # Initialising dictionary ini_dict = [{'a':1}, {'b':2}, {'c':3}] # pr
4 min read
Python | Flatten Tuples List to String
Sometimes, while working with data, we can have a problem in which we need to perform interconversion of data. In this, we can have a problem of converting tuples list to a single String. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + join() The combination of above functionalities can be used
7 min read
Python | Split flatten String List
Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split() + extend() The combination of a
7 min read
Python - Flatten Dictionary with List
Given a list and dictionary, flatten dictionary with keys and values at position of available element of key in list. Input : test_list = ["Gfg", "is", "Best", "For", "Geeks"], subs_dict = {"Gfg" : 7} Output : ['Gfg', 7, 'is', 'Best', 'For', 'Geeks'] Explanation : "Gfg" is replaced, followed by its value in dictionary. Input : test_list = ["Gfg", "
4 min read
Python Program to Flatten a Nested List using Recursion
Given a nested list, the task is to write a python program to flatten a nested list using recursion. Examples: Input: [[8, 9], [10, 11, 'geeks'], [13]] Output: [8, 9, 10, 11, 'geeks', 13] Input: [['A', 'B', 'C'], ['D', 'E', 'F']] Output: ['A', 'B', 'C', 'D', 'E', 'F'] Step-by-step Approach: Firstly, we try to initialize a variable into the linked l
3 min read
Python Program to Flatten a List without using Recursion
The task is to convert a nested list into a single list in Python i.e no matter how many levels of nesting are there in the Python list, all the nested have to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside. In other words, an element in a list c
7 min read
Python Program To Flatten A Multi-Level Linked List Depth Wise- Set 2
We have discussed flattening of a multi-level linked list where nodes have two pointers down and next. In the previous post, we flattened the linked list level-wise. How to flatten a linked list when we always need to process the down pointer before next at every node. Input: 1 - 2 - 3 - 4 | 7 - 8 - 10 - 12 | | | 9 16 11 | | 14 17 - 18 - 19 - 20 |
4 min read
Practice Tags :