Open In App

Python – Nested List to single value Tuple

Last Updated : 05 Dec, 2023
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.



Previous Article
Next Article

Similar Reads

Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python | Pair and combine nested list to tuple list
Sometimes we need to convert between the data types, primarily due to the reason of feeding them to some function or output. This article solves a very particular problem of pairing like indices in list of lists and then construction of list of tuples of those pairs. Let's discuss how to achieve the solution of this problem. Method #1 : Using zip()
10 min read
Python program to Flatten Nested List to Tuple List
Given a list of tuples with each tuple wrapped around multiple lists, our task is to write a Python program to flatten the container to a list of tuples. Input : test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]Output : [(4, 6), (7, 4), (10, 3)]Explanation : The surrounded lists are omitted around each tuple. Input : test_list = [[[(4, 6)]],
7 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in r
8 min read
Python Program to Merge tuple list by overlapping mid tuple
Given two lists that contain tuples as elements, the task is to write a Python program to accommodate tuples from the second list between consecutive tuples from the first list, after considering ranges present between both the consecutive tuples from the first list. Input : test_list1 = [(4, 8), (19, 22), (28, 30), (31, 50)], test_list2 = [(10, 12
11 min read
Python - Unnest single Key Nested Dictionary List
Sometimes, while working with Python data, we can have a problem in which we need to perform unnesting of all the dictionaries which have single nesting of keys, i.e a single key and value and can easily be pointed to outer key directly. This kind of problem is common in domains requiring data optimization. Let's discuss certain ways in which this
7 min read
Python - Convert List to Single valued Lists in Tuple
Conversion of data types is the most common problem across CS domain nowdays. One such problem can be converting List elements to single values lists in tuples. This can have application in data preprocessing domain. Let's discuss certain ways in which this task can be performed. Input : test_list = [1, 3, 5, 6, 7, 9] Output : ([1], [3], [5], [6],
7 min read