Open In App

Python | Unpacking nested tuples

Last Updated : 03 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python list of tuples, we can have a problem in which we require to unpack the packed tuples. This can have a possible application in web development. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using list comprehension This task can be performed using list comprehension in which we iterate for tuples and construct the desired tuple. This technique is useful in case we know the exact number of tuple elements and positioning. 

Python3




# Python3 code to demonstrate working of
# Unpacking nested tuples
# using list comprehension
 
# initialize list
test_list = [(4, (5, 'Gfg')), (7, (8, 6))]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Unpacking nested tuples
# using list comprehension
res = [(x, y, z) for x, (y, z) in test_list]
 
# printing result
print("The unpacked nested tuple list is : " + str(res))


Output : 

The original list is : [(4, (5, 'Gfg')), (7, (8, 6))]
The unpacked nested tuple list is : [(4, 5, 'Gfg'), (7, 8, 6)]

Time complexity: O(n), where n is the size of the input list “test_list”.
Auxiliary space: O(n), where n is the size of the input list “test_list”. This is because the program creates a new list “res” of the same size as “test_list” to store the unpacked tuples.

Method #2 : Using list comprehension + “*” operator Many times, there might be a case in which we don’t know the exact number of element in tuple and also the element count is variable among tuples. The “*” operator can perform the task of this variable unpacking. 

Python3




# Python3 code to demonstrate working of
# Unpacking nested tuples
# using list comprehension + * operator
 
# initialize list
test_list = [(4, (5, 'Gfg')), (7, (8, 6))]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Unpacking nested tuples
# using list comprehension + * operator
res = [(z, *x) for z, x in test_list]
 
# printing result
print("The unpacked nested tuple list is : " + str(res))


Output : 

The original list is : [(4, (5, 'Gfg')), (7, (8, 6))]
The unpacked nested tuple list is : [(4, 5, 'Gfg'), (7, 8, 6)]

The time complexity of this code is O(n), where n is the number of tuples in the input list. 

The auxiliary space complexity is also O(n), where n is the number of tuples in the input list.

Method #3: Using nested loops

  • Initialize an empty list ‘res’ to store the unpacked tuples
  • Iterate through the tuples in the original list using a for loop
    • Initialize a temporary list to store the unpacked tuple:
    • Iterate through the elements of the nested tuple using another for loop:
      • Append each element of the nested tuple to the temporary list:
    • Append the temporary list to the result list:
  • Print the unpacked nested tuple list:

Python3




# initialize list
test_list = [(4, (5, 'Gfg')), (7, (8, 6))]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Unpacking nested tuples using nested loops
res = []
for z, x in test_list:
    temp = [z]
    for item in x:
        temp.append(item)
    res.append(temp)
 
# printing result
print("The unpacked nested tuple list is : " + str(res))


Output

The original list is : [(4, (5, 'Gfg')), (7, (8, 6))]
The unpacked nested tuple list is : [[4, 5, 'Gfg'], [7, 8, 6]]

Time complexity: O(n*m), where n is the number of tuples in the original list and m is the maximum number of elements in a nested tuple.
Auxiliary space: O(n*m), because we are creating a temporary list for each nested tuple and appending it to the result list.

Method #4 : Using extend(),type(),tuple() methods

Approach

  1. Initiate a for loop to traverse list of nested tuples
  2. Initiate another for loop inside above for loop traverse each nested tuple
  3. In the nested tuple if the type is tuple append tuple elements to list and other elements to list
  4. Finally convert list to tuple and append it as part of output list
  5. Display output list

Python3




# Python3 code to demonstrate working of
# Unpacking nested tuples
 
# initialize list
test_list = [(4, (5, 'Gfg')), (7, (8, 6))]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Unpacking 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(tuple(x))
         
# printing result
print("The unpacked nested tuple list is : " + str(res))


Output

The original list is : [(4, (5, 'Gfg')), (7, (8, 6))]
The unpacked nested tuple list is : [(4, 5, 'Gfg'), (7, 8, 6)]

Time complexity: O(n*m), where n is the number of tuples in the original list and m is the maximum number of elements in a nested tuple.
Auxiliary space: O(n*m), because we are creating a temporary list for each nested tuple and appending it to the result list.

Method #6: Using generator expressions

Unpack the nested tuples using generator expressions. This approach is similar to using list comprehension, but it generates elements on the fly rather than creating a new list.

Step-by-step approach:

  • Create a list of nested tuples test_list.
  • Print the original list.
  • Use a generator expression to unpack the nested tuples.
  • The generator expression (x, y, z) for x, (y, z) in test_list iterates over each tuple in test_list, and unpacks the second element of the tuple using (y, z). It then yields a new tuple with three elements (x, y, z).
  • Convert the generator expression to a list using the list() function and assign the result to res.
  • Print the unpacked nested tuple list res.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Unpacking nested tuples
# using generator expressions
 
# initialize list
test_list = [(4, (5, 'Gfg')), (7, (8, 6))]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Unpacking nested tuples
# using generator expressions
res = ((x, y, z) for x, (y, z) in test_list)
 
# printing result
print("The unpacked nested tuple list is : " + str(list(res)))


Output

The original list is : [(4, (5, 'Gfg')), (7, (8, 6))]
The unpacked nested tuple list is : [(4, 5, 'Gfg'), (7, 8, 6)]

Time complexity: O(n), where n is the length of the input list test_list. 
Auxiliary space: O(1), as we are not creating a new list or using any additional memory to store the generator expression.



Previous Article
Next Article

Similar Reads

Python | How to Concatenate tuples to nested tuples
Sometimes, while working with tuples, we can have a problem in which we need to convert individual records into a nested collection yet remaining as separate element. Usual addition of tuples, generally adds the contents and hence flattens the resultant container, this is usually undesired. Let's discuss certain ways in which this problem is solved
6 min read
Unpacking a Tuple in Python
Python Tuples In python tuples are used to store immutable objects. Python Tuples are very similar to lists except to some situations. Python tuples are immutable means that they can not be modified in whole program. Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of value
3 min read
Python | Unpacking tuple of lists
Given a tuple of lists, write a Python program to unpack the elements of the lists that are packed inside the given tuple. Examples: Input : (['a', 'apple'], ['b', 'ball']) Output : ['a', 'apple', 'b', 'ball'] Input : ([1, 'sam', 75], [2, 'bob', 39], [3, 'Kate', 87]) Output : [1, 'sam', 75, 2, 'bob', 39, 3, 'Kate', 87] Approach #1 : Using reduce()
3 min read
Python | Unpacking dictionary keys into tuple
In certain cases, we might come into a problem in which we require to unpack dictionary keys to tuples. This kind of problem can occur in cases we are just concerned about the keys of dictionaries and wish to have a tuple of them. Let's discuss certain ways in which this task can be performed in Python. Example Input: {'Welcome': 1, 'to': 2, 'GFG':
4 min read
Python - Unpacking Values in Strings
Given a dictionary, unpack its values into a string. Input : test_str = "First value is {} Second is {}", test_dict = {3 : "Gfg", 9 : "Best"} Output : First value is Gfg Second is Best Explanation : After substitution, we get Gfg and Best as values. Input : test_str = "First value is {} Second is {}", test_dict = {3 : "G", 9 : "f"} Output : First v
3 min read
Unpacking arguments in Python
If you have used Python even for a few days now, you probably know about unpacking tuples. Well for starter, you can unpack tuples or lists to separate variables but that not it. There is a lot more to unpack in Python. Unpacking without storing the values: You might encounter a situation where you might not need all the values from a tuple but you
3 min read
Packing and Unpacking Arguments in Python
We use two operators * (for tuples) and ** (for dictionaries). Background Consider a situation where we have a function that receives four arguments. We want to make a call to this function and we have a list of size 4 with us that has all arguments for the function. If we simply pass a list to the function, the call doesn't work. C/C++ Code # A Py
5 min read
Python | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x')] Method #1 : List comprehension This is a naive
5 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Practice Tags :