Python - Split in Nested tuples
Last Updated :
15 Mar, 2023
Sometimes, while working with Python tuples, we can have a problem in which we need to perform split of elements in nested tuple, by a certain delimiter. This kind of problem can have application in different data domains. Let's discuss certain ways in which this task can be performed.
Input : test_list = [(3, ('Gfg', 'best', 6)), (10, ('CS', 'good', 9))]
Output : [[3, 'Gfg', 'best', 6], [10, 'CS', 'good', 9]]
Input : test_list = [(3, (1, 2, 3, 6))]
Output : [[3, 1, 2, 3, 6]]
Method #1 : Using list comprehension + unpack operator(*) The combination of above functions can be used to solve this problem. In this, we perform the task of unpacking the elements by delimiter using * operator and list comprehension to iterate and form pairs.
Python3
# Python3 code to demonstrate working of
# Split in Nested tuples
# Using list comprehension + unpack operator
# initializing list
test_list = [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]
# printing original list
print("The original list is : " + str(test_list))
# Split in Nested tuples
# Using list comprehension + unpack operator
res = [[a, *b] for a, b in test_list]
# printing result
print("The splitted elements : " + str(res))
Output : The original list is : [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]
The splitted elements : [[3, 'Gfg', 'best'], [10, 'CS', 'good'], [7, 'Gfg', 'better']]
Time complexity: O(n), where n is the length of the input list test_list. This is because the program iterates through each element of the input list only once to perform the list comprehension and unpacking operation.
Auxiliary space: O(n), where n is the length of the input list test_list. This is because the program creates a new list res with the same number of elements as the input list, which requires additional memory.
Method #2 : Using map() + list() The combination of above functions can be used to solve this problem. In this, we perform task of extending logic to each elements using map() and list() is used to pack the strings to different containers.
Python3
# Python3 code to demonstrate working of
# Split in Nested tuples
# map() + list()
# initializing list
test_list = [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]
# printing original list
print("The original list is : " + str(test_list))
# Split in Nested tuples
# map() + list()
res = []
for sub in test_list:
res.append(list(map(str, (*[sub[0]], *[*sub[1]]))))
# printing result
print("The splitted elements : " + str(res))
Output : The original list is : [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]
The splitted elements : [[3, 'Gfg', 'best'], [10, 'CS', 'good'], [7, 'Gfg', 'better']]
The time complexity of this code is O(n), where n is the length of the input list test_list.
The auxiliary space complexity of this code is also O(n).
Method #3: Using a nested loop and type conversion
This method iterates through each tuple in the list, and then through each element in the tuple. If an element is a tuple, it maps the str() function to each element in the tuple and appends the resulting tuple to sub_res. Otherwise, it converts the element to a string using str() and appends it directly to sub_res. Finally, sub_res is appended to res.
Python3
# initializing list
test_list = [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]
# printing original list
print("The original list is : " + str(test_list))
# Split in Nested tuples
# nested loop + type conversion
res = []
for tup in test_list:
sub_res = []
for elem in tup:
if isinstance(elem, tuple):
sub_res.append(tuple(map(str, elem)))
else:
sub_res.append(str(elem))
res.append(sub_res)
# printing result
print("The splitted elements : " + str(res))
OutputThe original list is : [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]
The splitted elements : [['3', ('Gfg', 'best')], ['10', ('CS', 'good')], ['7', ('Gfg', 'better')]]
The time complexity of this code is O(n*m), where n is the length of the input list and m is the maximum number of elements in any tuple.
The auxiliary space complexity of this code is O(n*m), since it creates a new list res of the same size as the input list, and then appends a new list to it for each tuple in the input list.
Method #5: Using a lambda function and reduce()
This code uses a lambda function in combination with the reduce() function to convert the elements of each tuple into a list of strings. The lambda function takes two arguments, a and b, and returns a list that combines the string representation of a with the string representation of each element in b. The reduce() function applies the lambda function to each tuple in test_list, producing a list of lists where each inner list contains the string representation of the original number and the string representation of each element in the nested tuple.
Step-by-step algorithm
1- Import the reduce() function from the functools module.
2- Define the input list test_list as a list of tuples.
3- Use the map() function to apply a lambda function to each tuple in test_list.
4- The lambda function takes each tuple as an input and returns a list of strings that represents the tuple elements.
5- Within the lambda function, use reduce() to iterate over the nested tuple elements and combine them into a single list of strings.
6- The reduce() function takes a lambda function that takes two arguments: an accumulator a and an element b.
7- The lambda function used in reduce() concatenates the string representation of a with the string representation of each element in b to produce a new list of strings.
8- The reduce() function iterates over the elements of the nested tuple, applying the lambda function to each pair of elements to produce a single list of strings.
9- The lambda function used in map() takes the output of reduce() and combines it with the original number in the tuple to produce a list that contains both the original number and the string representation of the nested tuple elements.
10- The map() function returns a list of lists, where each inner list contains the original number and the string representation of the nested tuple elements.
11- Convert the result to a standard Python list using the list() function.
12- Print the result using the print() function.
Python3
from functools import reduce
test_list = [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]
res = list(map(lambda x: reduce(lambda a, b: [str(a)] + [str(elem) for elem in b], x), test_list))
print("The splitted elements : " + str(res))
OutputThe splitted elements : [['3', 'Gfg', 'best'], ['10', 'CS', 'good'], ['7', 'Gfg', 'better']]
Time complexity: O(n*m), where n is the length of test_list and m is the maximum length of the nested tuples.
Auxiliary space: O(n*m), as it creates a list of lists that contains a string representation of each element in each tuple.
Method #6 : Using extend(),type() methods
Approach
- Convert nested tuple to list using extend() method
- Append list to output list
- Display output list
Python3
# Python3 code to demonstrate working of
# Split in Nested tuples
# initializing list
test_list = [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]
# printing original list
print("The original list is : " + str(test_list))
# Split in Nested tuples
res=[]
for i in test_list:
x=[]
for j in i:
if type(j) is tuple:
x.extend(list(j))
else:
x.append(j)
res.append(x)
# printing result
print("The splitted elements : " + str(res))
OutputThe original list is : [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]
The splitted elements : [[3, 'Gfg', 'best'], [10, 'CS', 'good'], [7, 'Gfg', 'better']]
Time complexity: O(n*m), where n is the length of test_list and m is the maximum length of the nested tuples.
Auxiliary space: O(n*m), as it creates a list of lists that contains a string representation of each element in each tuple.
Similar Reads
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 - Maximize Nested Tuples
Sometimes, while working with records, we can have a problem in which we require to perform an index-wise maximum of tuple elements. This can get complicated with tuple elements being tuples and inner elements again being tuples. Letâs discuss certain ways in which this problem can be solved. Method
8 min read
Python | Sort lists in tuple
Sometimes, while working with Python tuples, we can have a problem in which we need to sort the tuples which constitutes of lists and we need to sort each of them. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + sorted() + generator expression This task ca
5 min read
Python | Nested Tuples Subtraction
Sometimes, while working with records, we can have a problem in which we require to perform index-wise subtraction of tuple elements. This can get complicated with tuple elements being tuples and inner elements again being tuple. Letâs discuss certain ways in which this problem can be solved. Metho
7 min read
Addition in Nested Tuples - Python
Sometimes, while working with records, we can have a problem in which we require to perform index wise addition of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let's discuss certain ways in which this problem can be solved. Method #1: U
6 min read
Python | Chunk Tuples to N
Sometimes, while working with data, we can have a problem in which we may need to perform chunking of tuples each of size N. This is popular in applications in which we need to supply data in chunks. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension
4 min read
Python - Nested List to single value Tuple
Sometimes, while working with Python data, we can have problems in which we need to convert Python Nested lists to single values tuples. This kind of problem can have applications in domains such as web development and competitive programming. Let's discuss certain ways in which this task can be per
7 min read
Python | Split tuple into groups of n
Given a tuple, the task is to divide it into smaller groups of n. Let's discuss a few methods to accomplish a given task.Method #1: Using enumerate and range function Python3 # Python code to demonstrate # how to split tuple # into the group of k-tuples # initialising tuple ini_tuple = (1, 2, 3, 4,
3 min read
Sort Tuple of Lists in Python
The task of sorting a tuple of lists involves iterating through each list inside the tuple and sorting its elements. Since tuples are immutable, we cannot modify them directly, so we must create a new tuple containing the sorted lists. For example, given a tuple of lists a = ([2, 1, 5], [1, 5, 7], [
3 min read
How To Slice A List Of Tuples In Python?
In Python, slicing a list of tuples allows you to extract specific subsets of data efficiently. Tuples, being immutable, offer a stable structure. Use slicing notation to select ranges or steps within the list of tuples. This technique is particularly handy when dealing with datasets or organizing i
3 min read