Python | Pair and combine nested list to tuple list
Last Updated :
14 Apr, 2023
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() + list comprehension We can use zip function to link to each element’s like indices and list comprehension can be used to perform the logic behind the conversion to tuple and extending the logic to all the sublists.
Python3
test_list1 = [[ 1 , 4 , 5 ], [ 8 , 7 ], [ 2 ]]
test_list2 = [[ 'g' , 'f' , 'g' ], [ 'f' , 'r' ], [ 'u' ]]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
res = [(u, v) for x, y in zip (test_list1, test_list2)
for u, v in zip (x, y)]
print ( "The paired list of tuple is : " + str (res))
|
Output
The original list 1 : [[1, 4, 5], [8, 7], [2]]
The original list 2 : [['g', 'f', 'g'], ['f', 'r'], ['u']]
The paired list of tuple is : [(1, 'g'), (4, 'f'), (5, 'g'), (8, 'f'), (7, 'r'), (2, 'u')]
Time complexity: O(n), where n is the sum of the lengths of test_list1 and test_list2.
Auxiliary space : O(n), where n is the length of the result list.
Method #2 : Using zip() + itertools.chain.from_iterable() This problem can also be solved using the zip function along with the from_iterable function. The task performed by zip function remains the same but conversion to tuple and do it for all elements can be handled by from_iterable function.
Python3
from itertools import chain
test_list1 = [[ 1 , 4 , 5 ], [ 8 , 7 ], [ 2 ]]
test_list2 = [[ 'g' , 'f' , 'g' ], [ 'f' , 'r' ], [ 'u' ]]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
res = list ( zip (chain.from_iterable(test_list1),
chain.from_iterable(test_list2)))
print ( "The paired list of tuple is : " + str (res))
|
Output
The original list 1 : [[1, 4, 5], [8, 7], [2]]
The original list 2 : [['g', 'f', 'g'], ['f', 'r'], ['u']]
The paired list of tuple is : [(1, 'g'), (4, 'f'), (5, 'g'), (8, 'f'), (7, 'r'), (2, 'u')]
Time complexity: O(n), where n is the sum of the lengths of all sublists in the input lists test_list1 and test_list2.
Auxiliary space: O(n)
Method #3 : Using extend() and for loops
Python3
test_list1 = [[ 1 , 4 , 5 ], [ 8 , 7 ], [ 2 ]]
test_list2 = [[ 'g' , 'f' , 'g' ], [ 'f' , 'r' ], [ 'u' ]]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
res = []
a = []
b = []
for i in range ( 0 , len (test_list1)):
a.extend(test_list1[i])
b.extend(test_list2[i])
for i in range ( 0 , len (a)):
res.append((a[i],b[i]))
print ( "The paired list of tuple is : " + str (res))
|
Output
The original list 1 : [[1, 4, 5], [8, 7], [2]]
The original list 2 : [['g', 'f', 'g'], ['f', 'r'], ['u']]
The paired list of tuple is : [(1, 'g'), (4, 'f'), (5, 'g'), (8, 'f'), (7, 'r'), (2, 'u')]
Time Complexity : O(N*N)
Auxiliary Space : O(N)
Method#4: Using Recursive method.
Algorithm:
- Define a function pair_nested_lists(test_list1, test_list2) that takes two nested lists as input.
- Check if the length of test_list1 is zero, if yes then return an empty list.
- Otherwise, initialize an empty list res.
- Extract the first element of both lists test_list1 and test_list2 and assign it to variables a and b.
- Iterate through the range of length of a and for each index i, append a tuple (a[i], b[i]) to res.
- Recursively call the pair_nested_lists function on the remaining elements of both lists using slice notation [1:] and concatenate the resulting list with res.
- Return the final list res.
Python3
def pair_nested_lists(test_list1, test_list2):
if len (test_list1) = = 0 :
return []
else :
res = []
a = test_list1[ 0 ]
b = test_list2[ 0 ]
for i in range ( 0 , len (a)):
res.append((a[i], b[i]))
return res + pair_nested_lists(test_list1[ 1 :], test_list2[ 1 :])
test_list1 = [[ 1 , 4 , 5 ], [ 8 , 7 ], [ 2 ]]
test_list2 = [[ 'g' , 'f' , 'g' ], [ 'f' , 'r' ], [ 'u' ]]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
res = pair_nested_lists(test_list1, test_list2)
print ( "The paired list of tuple is : " + str (res))
|
Output
The original list 1 : [[1, 4, 5], [8, 7], [2]]
The original list 2 : [['g', 'f', 'g'], ['f', 'r'], ['u']]
The paired list of tuple is : [(1, 'g'), (4, 'f'), (5, 'g'), (8, 'f'), (7, 'r'), (2, 'u')]
Time Complexity : O(N*M), where N is the number of sublists in test_list1 and test_list2 and M is the maximum length of any sublist in both lists. This is because the function needs to iterate through all elements of the sublists in both lists and create a tuple for each element.
Auxiliary Space : O(N*M), as the function creates a new list res for each recursion level and the total number of tuples in the resulting list is n x m.
Method #5: Using a nested for loop.
Step-by-step approach:
- Initialize an empty list to store the paired tuples.
- Use a nested for loop to iterate through the sublists of both the given lists.
- Use the built-in function zip() to pair the elements of the sublists.
- Append the paired tuples to the empty list.
- Return the list containing the paired tuples.
Below is the implementation of the above approach:
Python3
test_list1 = [[ 1 , 4 , 5 ], [ 8 , 7 ], [ 2 ]]
test_list2 = [[ 'g' , 'f' , 'g' ], [ 'f' , 'r' ], [ 'u' ]]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
res = []
for i in range ( len (test_list1)):
for j in range ( len (test_list1[i])):
res.append((test_list1[i][j], test_list2[i][j]))
print ( "The paired list of tuple is : " + str (res))
|
Output
The original list 1 : [[1, 4, 5], [8, 7], [2]]
The original list 2 : [['g', 'f', 'g'], ['f', 'r'], ['u']]
The paired list of tuple is : [(1, 'g'), (4, 'f'), (5, 'g'), (8, 'f'), (7, 'r'), (2, 'u')]
Time complexity: O(n^2), where n is the length of the longest sublist, since we have to iterate through each element of each sublist.
Auxiliary space: O(n^2), since we need to store all the paired tuples in a list.
Method 6: Using map() with lambda function
Step-by-step explanation:
- We define the two input lists test_list1 and test_list2.
- We use map() with a lambda function to zip the two lists element-wise. The lambda function takes two arguments, x and y, and returns a list of tuples generated by the zip() function. We pass test_list1 and test_list2 as the two input sequences to map().
- We get a list of lists of tuples as the result of the map() function. We flatten this list of lists using a list comprehension, where we iterate over each sublist using two for loops, and append each tuple to a new list.
- We print the resulting paired list of tuples.
Python3
test_list1 = [[ 1 , 4 , 5 ], [ 8 , 7 ], [ 2 ]]
test_list2 = [[ 'g' , 'f' , 'g' ], [ 'f' , 'r' ], [ 'u' ]]
res = list ( map ( lambda x, y: list ( zip (x, y)), test_list1, test_list2))
res = [item for sublist in res for item in sublist]
print ( "The paired list of tuple is : " + str (res))
|
Output
The paired list of tuple is : [(1, 'g'), (4, 'f'), (5, 'g'), (8, 'f'), (7, 'r'), (2, 'u')]
Time complexity: O(n*m), where n is the length of the longest sub-list in test_list1 and test_list2, and m is the number of sub-lists in test_list1 and test_list2.
Auxiliary space: O(n*m), to store the resulting paired list of tuples.
Method 7: Using reduce():
Algorithm:
- Import the required modules – functools and itertools
- Initialize two nested lists test_list1 and test_list2 and Print the original lists
- Use reduce() with a lambda function to flatten both lists and pair their elements as a tuple.
- Store the result in res and Print the final paired list of tuples – res.
Below is the implementation of the above approach:
Python3
from functools import reduce
from itertools import chain
test_list1 = [[ 1 , 4 , 5 ], [ 8 , 7 ], [ 2 ]]
test_list2 = [[ 'g' , 'f' , 'g' ], [ 'f' , 'r' ], [ 'u' ]]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
res = reduce ( lambda x, y: x + [y],
list ( zip (chain.from_iterable(test_list1), chain.from_iterable(test_list2))), [])
res = [(res[i], res[i + 1 ]) for i in range ( 0 , len (res), 2 )]
print ( "The paired list of tuple is : " + str (res))
|
Output
The original list 1 : [[1, 4, 5], [8, 7], [2]]
The original list 2 : [['g', 'f', 'g'], ['f', 'r'], ['u']]
The paired list of tuple is : [((1, 'g'), (4, 'f')), ((5, 'g'), (8, 'f')), ((7, 'r'), (2, 'u'))]
Time Complexity: The time complexity of the given code is O(n), where n is the total number of elements in the nested lists. The reduce() function in the code runs in linear time complexity.
Space Complexity: The space complexity of the code is O(n), where n is the total number of elements in the nested lists. This is because we need to store all the elements of the flattened lists and the paired tuples in memory.
Method 8: Using heapq:
Algorithm:
- Initialize the two input lists test_list1 and test_list2.
- Convert all elements of test_list1 and test_list2 to strings using a nested list comprehension.
- Use heapq to merge the two nested lists using the merge() function.
- Zip the elements of the merged list to create tuples.
- Convert the first element of each tuple back to integers using a list comprehension.
- Print the final paired list of tuples.
Python3
import heapq
test_list1 = [[ 1 , 4 , 5 ], [ 8 , 7 ], [ 2 ]]
test_list2 = [[ 'g' , 'f' , 'g' ], [ 'f' , 'r' ], [ 'u' ]]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
test_list1 = [[ str (x) for x in lst] for lst in test_list1]
test_list2 = [[ str (x) for x in lst] for lst in test_list2]
merged_list = list (heapq.merge( * [ zip (test_list1[i], test_list2[i]) for i in range ( len (test_list1))]))
res = [( int (x[ 0 ]), x[ 1 ]) for x in merged_list]
print ( "The paired list of tuple is : " + str (res))
|
Output
The original list 1 : [[1, 4, 5], [8, 7], [2]]
The original list 2 : [['g', 'f', 'g'], ['f', 'r'], ['u']]
The paired list of tuple is : [(1, 'g'), (2, 'u'), (4, 'f'), (5, 'g'), (8, 'f'), (7, 'r')]
Time complexity:
The time complexity of this code is O(n log n) due to the use of heapq.merge() function which has a time complexity of O(n log n).
Space complexity:
The space complexity of this code is O(n) due to the creation of a new list to store the merged and paired tuples.
Similar Reads
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 ar
7 min read
Python | Convert list of tuples to list of list
Converting list of tuples to list of lists in Python is a task where each tuple is transformed into list while preserving its elements. This operation is commonly used when we need to modify or work with the data in list format instead of tuples. Using numpyNumPy makes it easy to convert a list of t
3 min read
Python - Add Custom Column to Tuple list
Sometimes, while working with Python records, we can have a problem in which we need to add custom column to tuples list. This kind of problem can have application in data domains such as web development. Lets discuss certain ways in which this task can be performed. Input : test_list = [(3, ), (7,
5 min read
Python List and Tuple Combination Programs
Lists and tuples are two of the most commonly used data structures in Python. While lists are mutable and allow modifications, tuples are immutable and provide a stable structure for storing data. This article explores various programs related to list and tuple combinations, covering topics like: So
6 min read
Convert Set of Tuples to a List of Lists in Python
Sets and lists are two basic data structures in programming that have distinct uses. It is sometimes necessary to transform a collection of tuples into a list of lists. Each tuple is converted into a list throughout this procedure, and these lists are subsequently compiled into a single, bigger list
3 min read
Convert List of Tuples To Multiple Lists in Python
When working with data in Python, it's common to encounter situations where we need to convert a list of tuples into separate lists. For example, if we have a list of tuples where each tuple represents a pair of related data points, we may want to split this into individual lists for easier processi
4 min read
Python - Convert a list into tuple of lists
When working with data structures in Python, there are times when we need to convert a list into a tuple of smaller lists. For example, given a list [1, 2, 3, 4, 5, 6], we may want to split it into a tuple of two lists like ([1, 2, 3], [4, 5, 6]). We will explore different methods to achieve this co
3 min read
Python | Convert list to indexed tuple list
Sometimes, while working with Python lists, we can have a problem in which we need to convert a list to tuple. This kind of problem have been dealt with before. But sometimes, we have it's variation in which we need to assign the index of the element along with element as a tuple. Let's discuss cert
3 min read
Convert List to Tuple in Python
The task of converting a list to a tuple in Python involves transforming a mutable data structure list into an immutable one tuple. Using tuple()The most straightforward and efficient method to convert a list into a tuple is by using the built-in tuple(). This method directly takes any iterable like
2 min read
Python | Convert Integral list to tuple list
Sometimes, while working with data, we can have a problem in which we need to perform type of interconversions of data. There can be a problem in which we may need to convert integral list elements to single element tuples. Let's discuss certain ways in which this task can be performed. Method #1 :
3 min read