Open In App

Python – Nested List to single value Tuple

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Example:

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, )]

Python Nested List to Single Value Tuple

Below are the ways by which we can convert nested lists to single-value tuples:

  • Using list comprehension ( For single nesting )
  • Using isinstance() + recursion
  • Using extend() method
  • Using Two nested loop
  • Using map and chain functions
  • Using reduce() function and add operator
  • Using NumPy

Flatten Nested List to Single-Value Tuples with List Comprehension

In this example, a nested list test_list is converted into a flat tuple container res using list comprehension, where each element from the nested lists is encapsulated in a one-value tuple. The result is a flattened representation of the original nested list.

Python3




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

Time complexity: O(n)
Auxiliary space: O(n)

Recursively Convert Nested List to Single-Value Tuples Using isinstance()

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. In this example, the function helper_func employs recursion and isinstance() to traverse the nested list test_list, creating a flattened tuple container res where each individual integer element is encapsulated in a one-value tuple. The result is a flattened representation of the original nested list.

Python3




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,)]

Time complexity: O(n)
Auxiliary space: O(n)

Convert Nested List to Single-Value Tuples Using extend() Method

In this example, we are using extend() and the nested list test_list is transformed into a flattened tuple container res using a combination of list comprehension and loops. The individual elements from the nested lists are extracted and enclosed in one-value tuples.

Python3




# 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
x = []
res = []
for i in test_list:
    x.extend(i)
for i in x:
    res.append((i,))
# 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,)]

Time complexity: O(n)
Auxiliary space: O(n) 

Convert Nested List to Single-Value Tuples with Two Nested Loops

The method used in the above program is using two nested for loops. The first for loop iterates over the sublists in the nested list, and the second for loop iterates over the values in each sublist. For each value, a single value tuple is created and appended to the single_value_tuple list. Finally, the single_value_tuple list is returned as the result.

Python3




def nested_list_to_single_value_tuple(nested_list):
    single_value_tuple = []
    for sublist in nested_list:
        for value in sublist:
            single_value_tuple.append((value,))
    return single_value_tuple
 
def main():
    test_list = [[5, 6], [4, 7, 10, 17]]
    result = nested_list_to_single_value_tuple(test_list)
    print("Single value tuple:", result)
 
    test_list = [[5, 6, 7, 8]]
    result = nested_list_to_single_value_tuple(test_list)
    print("Single value tuple:", result)
 
if __name__ == '__main__':
    main()


Output

Single value tuple: [(5,), (6,), (4,), (7,), (10,), (17,)]
Single value tuple: [(5,), (6,), (7,), (8,)]

Time complexity: O(m * n),  where m is the number of sublists in the nested list and n is the total number of values in the nested list.
Auxiliary space: O(n)

Nested List to Single Value Tuple Using map and chain functions

In this example, the nested list test_list is flattened into a list of one-value tuples using the map function with a lambda expression and the chain function from the itertools module. The result is a flattened representation of the original nested list, and the output is printed using print(result).

Python3




test_list = [[5, 6], [4, 7, 10], [12], [9, 11]]
# Using the map and chain functions from the itertools module
import itertools
result = list(map(lambda x: (x,), itertools.chain(*test_list)))
#output
print(result)
#this code is contributed by Asif_Shaik


Output

[(5,), (6,), (4,), (7,), (10,), (12,), (9,), (11,)]

Time complexity: O(n)
Auxiliary Space: O(n)

Python Convert Nested List to Tuple Using the reduce() and add Operator

In this example, the function nested_list_to_single_value_tuple utilizes the reduce function from the functools module to flatten the nested list test_list. The resulting flat list is then transformed into a list of one-value tuples, providing a flattened representation of the original nested list. The converted container is printed using print("The converted container : " + str(res))

Python3




# Python3 code to demonstrate working of
# Convert Nested List to 1 value Tuple
from functools import reduce
def nested_list_to_single_value_tuple(nested_list):
    flat_list = reduce(lambda x, y: x+y, nested_list)
    return [(x,) for x in flat_list]
 
 
# 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
 
res = nested_list_to_single_value_tuple(test_list)
# 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,)]

Time complexity: O(n^2)
Auxiliary Space: O(n)

Python Nested List to Single Value Tuple Using NumPy

In this example, the nested list test_list is flattened using a list comprehension, and each element is then encapsulated in a one-value tuple using another list comprehension.

Python3




import numpy as np
 
test_list = [[5, 6], [4, 7, 10], [12], [9, 11]]
 
# flatten the original list
flat_list = [item for sublist in test_list for item in sublist]
 
# convert each element to a tuple
res = [(i,) for i in flat_list]
 
# printing original list
print("The original list is : " + str(test_list))
 
# printing result
print("The converted container : " + str(res))
#This code is contributed by Vinay pinjala


Output:

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

Time Complexity : O(n*m), where n is the number of sublists and m is the maximum length of a sublist.
Auxiliary Space :O(nm), as the flattened list and tuple list both have nm elements.



Last Updated : 05 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads