Friday, September 20, 2024
Google search engine
HomeLanguagesPython – Nested List to single value Tuple

Python – Nested List to single value Tuple

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 ways in which this task can be performed. We iterate each inner list and convert each element as a separate tuple. This caters just to a single nesting. 

Python3




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

Time complexity: O(n), where n is the total number of elements in the nested list. This is because we are using a nested for loop to iterate over all elements in the nested list, which takes O(n) time.
Auxiliary space: O(n), because we are using a list comprehension to create a new list of tuples, each of which contains a single element from the original nested list. The size of this new list will be equal to the total number of elements in the nested list, so the space required is O(n).

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




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

Time complexity: O(n), where ‘n’ is the total number of elements in the nested list.
Auxiliary space: O(n), where ‘n’ is the total number of elements in the nested list. This is because the space used by the list ‘res’ is proportional to the number of elements in the nested list. Additionally, the recursive calls also consume space on the call stack. However, the space used by the call stack is also proportional to the number of elements in the nested list.

Method #3 : Using extend() method

Approach-

1-The provided Python code demonstrates how to convert a nested list into a list of one-value tuples.

2-The program first initializes a nested list called test_list containing four sublists. It then prints the original list.

3-Next, the program creates two empty lists x and res. It iterates over the sublists in test_list and extends x with their elements. This effectively flattens the nested list into a single list.

4-The program then iterates over the elements in x and appends each element to res as a one-value tuple using the syntax (i,).

5-Finally, the program prints the converted list of one-value tuples.

Python3




# Python3 code to demonstrate working of
# Convert Nested List to 1 value Tuple
 
# 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,)]

The time complexity of the given code is O(n), where n is the total number of elements in the nested list.

The auxiliary space complexity of the code is O(n), where n is the total number of elements in the nested list. 

Method 4: Using two nested loop

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), as we are using a list to store the single-value tuples. 

Method 5: Using map and chain functions

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)

Method 6: Using the reduce function and the add operator.

  1. Define the function nested_list_to_single_value_tuple with the input argument nested_list.
  2. Use the reduce function from functools module to flatten the nested list into a flat list.
  3. Create a new list comprehension to create a tuple of single value for each element in the flat list.
  4. Return the list of single value tuples.
  5. Call the function with the input list as an argument and store the result in a variable res.
  6. Print the original list and the converted container.

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: The time complexity of this function is O(n^2) because it uses the reduce function to flatten the nested list, which has a time complexity of O(n^2) in the worst case. The list comprehension has a time complexity of O(n), which is dominated by the reduce function. Therefore, the overall time complexity is O(n^2).
Auxiliary Space: The space complexity of this function is O(n) because it creates a new list to store the flattened list, and another list to store the single value tuples. The space required for both lists is proportional to the size of the input list, which gives a space complexity of O(n).

Method 7: using NumPy:

Algorithm :

1.Start by defining the input nested list.
2.Create an empty list to store the result.
3.Flatten the nested list into a single list using list comprehension or numpy.
4.Iterate over each element in the flattened list.
5.Convert each element to a tuple with a single value.
6.Append the resulting tuple to the result list.
7.Print the original list and the converted container.

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

The time complexity : O(n*m), where n is the number of sublists and m is the maximum length of a sublist.

The auxiliary space :O(nm), as the flattened list and tuple list both have nm elements.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments