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 - Maximum of Similar Keys in Tuples
Next article icon

Python – Similar index pairs in Tuple lists

Last Updated : 07 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with Python tuples, we can have a problem in which we need to perform similar index pairing. This kind of problem is peculiar, but can occur across certain domains. Let’s discuss certain way in which this task can be performed.

Input : test_list1 = [(5, ), (1, ), (8, ), (10, )] test_list2 = [(8, ), (1, ), (11, ), (9, )] 
Output : [[(5, 8)], [(1, 1)], [(8, 11)], [(10, 9)]] 

Input : test_list1 = [(5, 6, 7, 6)] test_list2 = [(8, 6, 7, 9)] 
Output : [[(5, 8), (6, 6), (7, 7), (6, 9)]]

Method 1: Using list comprehension + zip() The combination of above functions can be used to solve this problem. In this, we perform the task of zipping similar index elements using zip() and list comprehension is used to compile all the pairs. 

Python3




# Python3 code to demonstrate working of
# Similar index pairs in Tuple lists
# Using list comprehension + zip()
 
# initializing lists
test_list1 = [(5, 6), (1, 2), (8, 9), (10, 33)]
test_list2 = [(8, 7), (1, 3), (11, 23), (9, 4)]
 
# printing original list
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Similar index pairs in Tuple lists
# Using list comprehension + zip()
res = [list(zip(a, b)) for a, b in zip(test_list1, test_list2)]
 
# printing result
print("The paired tuples : " + str(res))
 
 
Output : 
The original list 1 is : [(5, 6), (1, 2), (8, 9), (10, 33)] The original list 2 is : [(8, 7), (1, 3), (11, 23), (9, 4)] The paired tuples : [[(5, 8), (6, 7)], [(1, 1), (2, 3)], [(8, 11), (9, 23)], [(10, 9), (33, 4)]]

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. The list comprehension + zip() is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n), the algorithm uses an additional list to store the result, thus consuming linear space which is O(n).

Method 2: Using for loop

Explanation:

  • Initialize two lists test_list1 and test_list2 as given in the problem.
  • Print the original lists using the print() function.
  • Initialize an empty list result that will contain the paired tuples.
  • Using a nested for loop, iterate over each index of test_list1 and extract corresponding elements from test_list1 and test_list2.
  • Create a tuple of the extracted elements and append it to a temporary list temp.
  • Append the temporary list temp to the result list.
  • Finally, print the result list containing the paired tuples.

Python3




# initializing lists
test_list1 = [(5, 6), (1, 2), (8, 9), (10, 33)]
test_list2 = [(8, 7), (1, 3), (11, 23), (9, 4)]
 
# printing original list
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Similar index pairs in Tuple lists
result = []
for i in range(len(test_list1)):
    temp = []
    for j in range(len(test_list1[i])):
        temp.append((test_list1[i][j], test_list2[i][j]))
    result.append(temp)
 
# printing result
print("The paired tuples : " + str(result))
 
 
Output
The original list 1 is : [(5, 6), (1, 2), (8, 9), (10, 33)] The original list 2 is : [(8, 7), (1, 3), (11, 23), (9, 4)] The paired tuples : [[(5, 8), (6, 7)], [(1, 1), (2, 3)], [(8, 11), (9, 23)], [(10, 9), (33, 4)]]

Time complexity: O(n^2), where n is the length of the input lists.
Auxiliary space: O(n^2), since we are creating a nested list to store the paired tuples.

Method 3: Using reduce:

Algorithm:

  1. Initialize an empty list called ‘result’.
  2. For each index ‘i’ in range from 0 to the length of ‘test_list1’:
    a. Initialize an empty list called ‘temp’.
    b. For each index ‘j’ in range from 0 to the length of sub-list at index ‘i’ of ‘test_list1’:
    i. Create a tuple of elements at index ‘j’ of sub-list at index ‘i’ of ‘test_list1’ and sub-list at index ‘i’ of ‘test_list2’, respectively.
    ii. Append the created tuple to ‘temp’.
    c. Append ‘temp’ to ‘result’.
  3. Print the final list ‘result’.
     

Python3




from functools import reduce
 
# initializing lists
test_list1 = [(5, 6), (1, 2), (8, 9), (10, 33)]
test_list2 = [(8, 7), (1, 3), (11, 23), (9, 4)]
 
# print original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# using reduce to get paired tuples
result = reduce(lambda acc, curr: acc + [[(curr[0][i], curr[1][i]) for i in range(len(curr[0]))]], zip(test_list1, test_list2), [])
 
# print result
print("The paired tuples : " + str(result))
#This code is contributed by Rayudu.
 
 
Output
The original list 1 is : [(5, 6), (1, 2), (8, 9), (10, 33)] The original list 2 is : [(8, 7), (1, 3), (11, 23), (9, 4)] The paired tuples : [[(5, 8), (6, 7)], [(1, 1), (2, 3)], [(8, 11), (9, 23)], [(10, 9), (33, 4)]]

Time Complexity: O(n^2), where ‘n’ is the length of each sublist in ‘test_list1’ and ‘test_list2’, since there are nested loops iterating over each element in both sublists.

Space Complexity: O(n^2), where ‘n’ is the length of each sublist in ‘test_list1’ and ‘test_list2’, since the result list is a nested list containing tuples of the same size as the sublists in the input lists.



Next Article
Python - Maximum of Similar Keys in Tuples
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python List-of-Tuples
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Count similar pair in Dual List
    Sometimes, while working with data, we can have a problem in which we receive the dual elements pair and we intend to find pairs of similar elements and it's frequency. This kind of data is usually useful in data domains. Let's discuss certain ways in which this task can be performed.Method #1 : Usi
    4 min read
  • Python | Sort lists in tuple
    Sometimes, while working with Python tuples, we can have a problem in which we need to sort the tuples which constitutes of lists and we need to sort each of them. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + sorted() + generator expression This task ca
    4 min read
  • Python - Maximum of Similar Keys in Tuples
    Sometimes, while working with Python tuples, we can have a problem in which we need to perform maximum of all values of the equal keys in Tuple list. This kind of application in useful in many domains such as web development and day-day programming. Let's discuss certain ways in which this task can
    4 min read
  • Python | Unique pairs in list
    Sometimes, while working with python list, we can have a binary matrix ( Nested list having 2 elements ). And we can have a problem in which we need to find the uniqueness of a pair. A pair is unique irrespective of order, it doesn't appear again in list. Let's discuss certain way in which this task
    6 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
  • Python - Extract Similar pairs from List
    Sometimes, while working with Python lists, we can have a problem in which we need to perform extraction of all the elements pairs in list. This kind of problem can have application in domains such as web development and day-day programming. Let's discuss certain ways in which this task can be perfo
    5 min read
  • Python - Convert Lists into Similar key value lists
    Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corre
    12 min read
  • Sort Tuple of Lists in Python
    The task of sorting a tuple of lists involves iterating through each list inside the tuple and sorting its elements. Since tuples are immutable, we cannot modify them directly, so we must create a new tuple containing the sorted lists. For example, given a tuple of lists a = ([2, 1, 5], [1, 5, 7], [
    3 min read
  • Python - Elements with K lists similar index value
    Sometimes, while working with data, we can have a problem in which we need to get elements which are similar in K lists in particular index. This can have application in many domains such as day-day and other domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using z
    5 min read
  • Python - Cross Pairing in Tuple List
    Given 2 tuples, perform cross pairing of corresponding tuples, convert to single tuple if 1st element of both tuple matches. Input : test_list1 = [(1, 7), (6, 7), (8, 100), (4, 21)], test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)] Output : [(7, 3)] Explanation : 1 occurs as tuple element at pos. 1 in
    5 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