Skip to content
Related Articles

Related Articles

Python – Nested List to single value Tuple
  • Last Updated : 03 Jul, 2020

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

Input : test_list = [[5, 6], [4, 7, 10, 17]]
Output : [(5, ), (6, ), (4, ), (7, ), (10, ), (17, )]

Input : test_list = [[5, 6, 7, 8]]
Output : [(5, ), (6, ), (7, ), (8, )]

Method #1 : Using list comprehension ( For single nesting )
This is one of the way in which this task can be performed. We iterate each inner list and convert each element as separate tuple. This caters just for a single nesting.




# Python3 code to demonstrate working of 
# Convert Nested List to 1 value Tuple
# Using list comprehension
  
# initializing list
test_list = [[5, 6], [4, 7, 10], [12], [9, 11]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Convert Nested List to 1 value Tuple
# Using list comprehension
res = [(ele, ) for sub in test_list for ele in sub]
  
# printing result 
print("The converted container : " + str(res)) 
Output :



The original list is : [[5, 6], [4, 7, 10], [12], [9, 11]]
The converted container : [(5, ), (6, ), (4, ), (7, ), (10, ), (12, ), (9, ), (11, )]

 

Method #2 : Using isinstance() + recursion
The combination of above functions can be used to solve this problem. In this, we perform the task of flattening and conversion using isinstance() and recursion to cater the case of random nesting as well.




# Python3 code to demonstrate working of 
# Convert Nested List to 1 value Tuple
# Using isinstance() + recursion
  
# helper_fnc
def hlper_fnc(test_list):
    res = []
    if isinstance(test_list, list):
        for ele in test_list:
            res.extend(hlper_fnc(ele))
    elif isinstance(test_list, int):
        res.append((test_list, ))
    return res
  
# initializing list
test_list = [[5, [6]], [4, 7, [10, 45]], [12], [9, 11]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Convert Nested List to 1 value Tuple
# Using isinstance() + recursion
res = hlper_fnc(test_list)
  
# printing result 
print("The converted container : " + str(res)) 
Output :
The original list is : [[5, [6]], [4, 7, [10, 45]], [12], [9, 11]]
The converted container : [(5, ), (6, ), (4, ), (7, ), (10, ), (45, ), (12, ), (9, ), (11, )]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :