+

Python | Unpacking nested tuples

Method # 1: Using List Comprehension
This task can be accomplished using list comprehension, in which we iterate over the tuples and create the desired tuple. This method is useful when we know the exact number of elements of the tuple and the positioning.

# Python3 code to demonstrate how it works
# Unpacking nested tuples
# using comprehension list

 
# initialize the list

test_list = [( 4 , ( 5 , `Gfg` )), ( 7 , ( 8 , 6 ))]

  
# print original list

print ( "The original list is:" + str (test_list))

 
# Unpacking nested tuples
# using comprehension list

res = [(x, y, z) for x, (y, z) in test_list]

 
# print 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)] 

Method # 2: Using a comprehension list + " * " operator
In many cases, there may be a case where we do not know the exact number of elements in a tuple, and the number of elements variables among tuples. The "*" operator can perform the task of unpacking this variable.

# Python3 code to demonstrate how it works
# Unpack nested tuples
# using comprehension list + * operator

 
# initialize the list

test_list = [( 4 , ( 5 , ` Gfg` )), ( 7 , ( 8 , 6 ))]

 < br /> # printing the original list

print ( "The original list is:" + str (test_list))

 
# Unpacking nested tuples
# using comprehension list + * operator

res = [(z, * x) for z, x in test_list]

 
# print result

print ( "The unpacked nested t uple 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)]                                        
             
                
Get Solution for free from DataCamp guru