Open In App

Python – Split in Nested tuples

Last Updated : 15 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 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))


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*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))


Output

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.

Method #6 : Using extend(),type() methods

Approach

  1. Convert nested tuple to list using extend() method
  2. Append list to output list
  3. 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))


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*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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads