Python | Unpacking nested tuples

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.