# 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() + 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

 `# Python3 code to demonstrate ` `# Pairing and combining nested list to tuple list ` `# using zip() + list comprehension `   `# initializing lists ` `test_list1 ``=` `[[``1``, ``4``, ``5``], [``8``, ``7``], [``2``]] ` `test_list2 ``=` `[[``'g'``, ``'f'``, ``'g'``], [``'f'``, ``'r'``], [``'u'``]] `   `# printing original lists ` `print``(``"The original list 1 : "` `+` `str``(test_list1)) ` `print``(``"The original list 2 : "` `+` `str``(test_list2)) `   `# using zip() + list comprehension ` `# Pairing and combining nested list to tuple list ` `res ``=` `[(u, v) ``for` `x, y ``in` `zip``(test_list1, test_list2) ` `                            ``for` `u, v ``in` `zip``(x, y)] `   `# print result ` `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

 `# Python3 code to demonstrate ` `# Pairing and combining nested list to tuple list ` `# using zip() + itertools.chain.from_iterable() ` `from` `itertools ``import` `chain `   `# initializing lists ` `test_list1 ``=` `[[``1``, ``4``, ``5``], [``8``, ``7``], [``2``]] ` `test_list2 ``=` `[[``'g'``, ``'f'``, ``'g'``], [``'f'``, ``'r'``], [``'u'``]] `   `# printing original lists ` `print``(``"The original list 1 : "` `+` `str``(test_list1)) ` `print``(``"The original list 2 : "` `+` `str``(test_list2)) `   `# using zip() + itertools.chain.from_iterable() ` `# Pairing and combining nested list to tuple list ` `res ``=` `list``(``zip``(chain.from_iterable(test_list1), ` `            ``chain.from_iterable(test_list2))) `   `# print result ` `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

 `# Python3 code to demonstrate` `# Pairing and combining nested list to tuple list` `# using zip() + list comprehension`   `# initializing lists` `test_list1 ``=` `[[``1``, ``4``, ``5``], [``8``, ``7``], [``2``]]` `test_list2 ``=` `[[``'g'``, ``'f'``, ``'g'``], [``'f'``, ``'r'``], [``'u'``]]`   `# printing original lists` `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 result` `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:

1. Define a function pair_nested_lists(test_list1, test_list2) that takes two nested lists as input.
2. Check if the length of test_list1 is zero, if yes then return an empty list.
3. Otherwise, initialize an empty list res.
4. Extract the first element of both lists test_list1 and test_list2 and assign it to variables a and b.
5. Iterate through the range of length of a and for each index i, append a tuple (a[i], b[i]) to res.
6. 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.
7. Return the final list res.

## Python3

 `# Python3 code to demonstrate` `# Pairing and combining nested list to tuple list` `# using recursive function`     `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``:])`     `# initializing lists` `test_list1 ``=` `[[``1``, ``4``, ``5``], [``8``, ``7``], [``2``]]` `test_list2 ``=` `[[``'g'``, ``'f'``, ``'g'``], [``'f'``, ``'r'``], [``'u'``]]`   `# printing original lists` `print``(``"The original list 1 : "` `+` `str``(test_list1))` `print``(``"The original list 2 : "` `+` `str``(test_list2))`   `# using recursion` `# Pairing and combining nested list to tuple list` `res ``=` `pair_nested_lists(test_list1, test_list2)`     `# print result` `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

 `# Python3 code to demonstrate ` `# Pairing and combining nested list to tuple list ` `# using nested for loop`   `# initializing lists ` `test_list1 ``=` `[[``1``, ``4``, ``5``], [``8``, ``7``], [``2``]] ` `test_list2 ``=` `[[``'g'``, ``'f'``, ``'g'``], [``'f'``, ``'r'``], [``'u'``]] `   `# printing original lists ` `print``(``"The original list 1 : "` `+` `str``(test_list1)) ` `print``(``"The original list 2 : "` `+` `str``(test_list2)) `   `# using nested for loop` `# Pairing and combining nested list to tuple list ` `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 result ` `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:

1. We define the two input lists test_list1 and test_list2.
2. 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().
3. 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.
4. 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:

1. Import the required modules – functools and itertools
2. Initialize two nested lists test_list1 and test_list2 and Print the original lists
3. Use reduce() with a lambda function to flatten both lists and pair their elements as a tuple.
4. 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`   `# initializing lists` `test_list1 ``=` `[[``1``, ``4``, ``5``], [``8``, ``7``], [``2``]]` `test_list2 ``=` `[[``'g'``, ``'f'``, ``'g'``], [``'f'``, ``'r'``], [``'u'``]]`   `# printing original lists` `print``(``"The original list 1 : "` `+` `str``(test_list1))` `print``(``"The original list 2 : "` `+` `str``(test_list2))`   `# using reduce() + lambda function` `res ``=` `reduce``(``lambda` `x, y: x ``+` `[y],` `             ``list``(``zip``(chain.from_iterable(test_list1), chain.from_iterable(test_list2))), [])`   `# convert list of tuples to list of paired tuples` `res ``=` `[(res[i], res[i``+``1``]) ``for` `i ``in` `range``(``0``, ``len``(res), ``2``)]`   `# print result` `print``(``"The paired list of tuple is : "` `+` `str``(res))`   `# This code is contributed by Jyothi pinjala.`

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:

1. Initialize the two input lists test_list1 and test_list2.
2. Convert all elements of test_list1 and test_list2 to strings using a nested list comprehension.
3. Use heapq to merge the two nested lists using the merge() function.
4. Zip the elements of the merged list to create tuples.
5. Convert the first element of each tuple back to integers using a list comprehension.
6. Print the final paired list of tuples.

## Python3

 `import` `heapq`   `# initializing lists` `test_list1 ``=` `[[``1``, ``4``, ``5``], [``8``, ``7``], [``2``]]` `test_list2 ``=` `[[``'g'``, ``'f'``, ``'g'``], [``'f'``, ``'r'``], [``'u'``]]` `# printing original lists` `print``(``"The original list 1 : "` `+` `str``(test_list1))` `print``(``"The original list 2 : "` `+` `str``(test_list2))` `# convert elements to string in the nested lists` `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]`   `# using heapq to merge nested lists and then pairing` `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]`   `# printing result` `print``(``"The paired list of tuple is : "` `+` `str``(res))` `#This code is contributed by Jyothi pinjala.`

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.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!