Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python List and Tuple Combination Programs
Next article icon

Python | Pair and combine nested list to tuple list

Last Updated : 14 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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.



Next Article
Python List and Tuple Combination Programs
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

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
  • Python - Add list elements to tuples list
    Sometimes, while working with Python tuples, we can have a problem in which we need to add all the elements of a particular list to all tuples of a list. This kind of problem can come in domains such as web development and day-day programming. Let's discuss certain ways in which this task can be don
    6 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
  • 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 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences