Python program to Flatten Nested List to Tuple List
Last Updated :
07 Apr, 2023
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, 4)]]]]
Output : [(4, 6), (7, 4)]
Explanation : The surrounded lists are omitted around each tuple.
Method #1 : Using recursion + isinstance()
In this, the container wrapping is tested to be list using isinstance(). The recursion strategy is used to check for repeated flattening of the list till tuple.
step-by-step approach of the given program:
- Define an empty list res outside the function remove_lists(). This list will be used to store the flattened elements of the input list.
- Define the function remove_lists(test_list) that takes a list as input. This function will recursively flatten the list.
- Iterate over the elements of test_list using a for loop.
- Check if the current element is a list or not using the isinstance() function. If it is a list, call the remove_lists() function recursively with the current element as input. This will flatten the nested list.
- If the current element is not a list, append it to the res list.
- Return the res list.
- Initialize the input list test_list with some nested tuples.
- Print the original list test_list.
- Call the function remove_lists() with test_list as input. This will flatten the nested list recursively and store the flattened elements in the res list.
- Print the flattened list.
- End of the program.
Python3
# Python3 code to demonstrate working of
# Multiflatten Tuple List
# Using recursion + isinstance()
res = []
def remove_lists(test_list):
for ele in test_list:
# checking for wrapped list
if isinstance(ele, list):
remove_lists(ele)
else:
res.append(ele)
return res
# initializing list
test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
# printing original list
print("The original list is : " + str(test_list))
# calling recursive function
res = remove_lists(test_list)
# printing result
print("The Flattened container : " + str(res))
OutputThe original list is : [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
The Flattened container : [(4, 6), (7, 4), (10, 3)]
Time Complexity: O(n), where n is the total number of elements in the nested tuple list.
Auxiliary Space: O(n), where n is the total number of elements in the nested tuple list.
Method #2 : Using yield + recursion
This method performs a similar task using recursion. The generator is used to process intermediate results using yield keyword.
Python3
# Python3 code to demonstrate working of
# Multiflatten Tuple List
# Using yield + recursion
def remove_lists(test_list):
if isinstance(test_list, list):
# return intermediate to recursive function
for ele in test_list:
yield from remove_lists(ele)
else:
yield test_list
# initializing list
test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
# printing original list
print("The original list is : " + str(test_list))
# calling recursive function
res = list(remove_lists(test_list))
# printing result
print("The Flattened container : " + str(res))
OutputThe original list is : [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
The Flattened container : [(4, 6), (7, 4), (10, 3)]
Time complexity: O(n), where n is the total number of elements in the input list.
Auxiliary space: O(m), where m is the maximum depth of nested lists in the input list.
Method #3 : Using replace(),split(),list(),map(),tuple() methods
Python3
# Python3 code to demonstrate working of
# Multiflatten Tuple List
# initializing list
test_list = [[[(4,6)]], [[[(7,4)]]], [[[[(10,3)]]]]]
res=[]
for i in test_list:
i=str(i)
i=i.replace("[","")
i=i.replace("]","")
i=i.replace("(","")
i=i.replace(")","")
x=i.split(",")
x=tuple(map(int,x))
res.append(x)
# printing original list
print("The original list is : " + str(test_list))
# printing result
print("The Flattened container : " + str(res))
OutputThe original list is : [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
The Flattened container : [(4, 6), (7, 4), (10, 3)]
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #4 : Using type() and recursion
Python3
# Python3 code to demonstrate working of
# Multiflatten Tuple List
res = []
def remove_lists(test_list):
for ele in test_list:
if type(ele) is list:
remove_lists(ele)
else:
res.append(ele)
return res
# initializing list
test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
# printing original list
print("The original list is : " + str(test_list))
# calling recursive function
res = remove_lists(test_list)
# printing result
print("The Flattened container : " + str(res))
OutputThe original list is : [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
The Flattened container : [(4, 6), (7, 4), (10, 3)]
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #5: Using itertools.chain() and recursion
Use the itertools.chain() function to flatten a nested list by recursively iterating over its elements using a generator function (flatten_list()) with the yield from statement. The remove_lists() function then applies itertools.chain.from_iterable() to the output of flatten_list() and returns a list containing all the flattened elements.
STEPS:
- First, we import the itertools module.
- Next, we define a function called flatten_list(lst) which takes a list as input and flattens it. This function uses a recursive approach to flatten nested lists. It checks whether the current item is a list or not. If it is a list, it calls the flatten_list() function again with that list as input, otherwise it yields the item.
- We define another function called remove_lists(test_list) which takes a nested list as input and returns a flattened list. This function uses the chain.from_iterable() method from itertools to concatenate all the nested lists into a single flattened list. It also calls the flatten_list() function to flatten the nested lists.
- We initialize a nested list called test_list which contains tuples.
- We print the original nested list.
- We call the remove_lists() function with test_list as input and store the flattened list in a variable called res.
- We print the flattened list.
Python3
import itertools
def flatten_list(lst):
for item in lst:
if isinstance(item, list):
yield from flatten_list(item)
else:
yield item
def remove_lists(test_list):
return list(itertools.chain.from_iterable(flatten_list(test_list)))
# initializing list
test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
# printing original list
print("The original list is : " + str(test_list))
# calling recursive function
res = remove_lists(test_list)
# printing result
print("The Flattened container : " + str(res))
OutputThe original list is : [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
The Flattened container : [4, 6, 7, 4, 10, 3]
Time complexity: O(n), where n is the total number of elements in the input list.
Auxiliary space: O(n), as the flatten_list() function uses recursion to iterate over the elements of the list, and each recursive call creates a new stack frame with local variables.
Method #6: Using stack and iteration
Step-by-step approach:
- Create an empty stack and append the input list test_list to it.
- Create an empty list res.
- While the stack is not empty:
a. Pop the top element ele from the stack.
b. If ele is a list, append its elements to the stack.
c. If ele is not a list, append it to res. - Return res.
Below is the implementation of the above approach:
Python3
def remove_lists(test_list):
# create an empty stack and append the input list to it
stack = [test_list]
# create an empty list to store the flattened elements
res = []
# while the stack is not empty
while stack:
# pop the top element from the stack
ele = stack.pop()
# if the element is a list, append its elements to the stack
if isinstance(ele, list):
stack += ele
# if the element is not a list, append it to the result list
else:
res.append(ele)
# return the flattened list
return res
# initializing list
test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
# printing original list
print("The original list is : " + str(test_list))
# calling function
res = remove_lists(test_list)
# printing result
print("The Flattened container : " + str(res))
OutputThe original list is : [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
The Flattened container : [(10, 3), (7, 4), (4, 6)]
Time complexity: O(n), where n is the total number of elements in the input list.
Auxiliary space: O(n), where n is the total number of elements in the input list.
Similar Reads
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,
3 min read
Python | Pair and combine nested list to tuple list
Sometimes we need to convert between the data types, primarily due to the reason of feeding them to some function or output. This article solves a very particular problem of pairing like indices in list of lists and then construction of list of tuples of those pairs. Let's discuss how to achieve the
10 min read
Flatten tuple of List to tuple - Python
The task of flattening a tuple of lists to a tuple in Python involves extracting and combining elements from multiple lists within a tuple into a single flattened tuple. For example, given tup = ([5, 6], [6, 7, 8, 9], [3]), the goal is to flatten it into (5, 6, 6, 7, 8, 9, 3). Using itertools.chain(
3 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is fo
8 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]
8 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 l
7 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
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 performe
7 min read
Python | Convert list of tuples to list of list
Converting list of tuples to list of lists in Python is a task where each tuple is transformed into list while preserving its elements. This operation is commonly used when we need to modify or work with the data in list format instead of tuples.Using numpyNumPy makes it easy to convert a list of tu
3 min read
Python - List of tuples to multiple lists
Converting a list of tuples into multiple lists involves separating the tuple elements into individual lists. This can be achieved using methods like zip(), list comprehensions or loops, each offering a simple and efficient way to extract and organize the data.Using zip()zip() function is a concise
3 min read