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:
Print a List of Tuples in Python
Next article icon

Python – All pair combinations of 2 tuples

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

Sometimes, while working with Python tuples data, we can have a problem in which we need to extract all possible combination of 2 argument tuples. This kind of application can come in Data Science or gaming domains. Let’s discuss certain ways in which this task can be performed.

Input : test_tuple1 = (7, 2), test_tuple2 = (7, 8) 
Output : [(7, 7), (7, 8), (2, 7), (2, 8), (7, 7), (7, 2), (8, 7), (8, 2)] 

Input : test_tuple1 = (9, 2), test_tuple2 = (7, 8) 
Output : [(9, 7), (9, 8), (2, 7), (2, 8), (7, 9), (7, 2), (8, 9), (8, 2)]

Method #1 : Using list comprehension This is one of the ways in which this task can be performed. In this, we perform task of forming one index combination in one pass, in other pass change the index, and add to the initial result list. 

Python3




# Python3 code to demonstrate working of
# All pair combinations of 2 tuples
# Using list comprehension
 
# initializing tuples
test_tuple1 = (4, 5)
test_tuple2 = (7, 8)
 
# printing original tuples
print("The original tuple 1 : " + str(test_tuple1))
print("The original tuple 2 : " + str(test_tuple2))
 
# All pair combinations of 2 tuples
# Using list comprehension
res =  [(a, b) for a in test_tuple1 for b in test_tuple2]
res = res +  [(a, b) for a in test_tuple2 for b in test_tuple1]
 
# printing result
print("The filtered tuple : " + str(res))
 
 
Output : 
The original tuple 1 : (4, 5) The original tuple 2 : (7, 8) The filtered tuple : [(4, 7), (4, 8), (5, 7), (5, 8), (7, 4), (7, 5), (8, 4), (8, 5)]

Time complexity: O(n^2), where n is the length of the tuples. The nested loop results in iterating through each element in both tuples.
Auxiliary space: O(n^2), the resulting list ‘res’ has all pair combinations of the elements in the tuples.
 

Method #2 : Using chain() + product() The combination of above functions provide yet another way to solve this problem. In this, we perform task of pair creation using product() and chain() is used to add both the results from product() used twice. 

Python3




# Python3 code to demonstrate working of
# All pair combinations of 2 tuples
# Using chain() + product()
from itertools import chain, product
 
# initializing tuples
test_tuple1 = (4, 5)
test_tuple2 = (7, 8)
 
# printing original tuples
print("The original tuple 1 : " + str(test_tuple1))
print("The original tuple 2 : " + str(test_tuple2))
 
# All pair combinations of 2 tuples
# Using chain() + product()
res = list(chain(product(test_tuple1, test_tuple2), product(test_tuple2, test_tuple1)))
 
# printing result
print("The filtered tuple : " + str(res))
 
 
Output : 
The original tuple 1 : (4, 5) The original tuple 2 : (7, 8) The filtered tuple : [(4, 7), (4, 8), (5, 7), (5, 8), (7, 4), (7, 5), (8, 4), (8, 5)]

Time complexity: O(2n^2), where n is the length of the tuples
Auxiliary space: O(n^2), as the result list stores all possible pair combinations of the two input tuples.

Method #3 : Using itertools.product(): 

Algorithm:

1.Initialize two tuples, “test_tuple1” and “test_tuple2”.
2.Create an empty list called “res”.
3.Use two nested loops to iterate through all pairs of elements in the two tuples.
4.For each pair, create a new tuple and append it to the “res” list.
5.Return the “res” list.
6.Print the resulting list.

Python3




import itertools
 
# initializing tuples
test_tuple1 = (4, 5)
test_tuple2 = (7, 8)
 
# printing original tuples
print("The original tuple 1 : " + str(test_tuple1))
print("The original tuple 2 : " + str(test_tuple2))
 
# generating all pair combinations of 2 tuples using list comprehension
res = [(a, b) for a in test_tuple1 for b in test_tuple2] + [(a, b) for a in test_tuple2 for b in test_tuple1]
 
# printing result
print("All pair combinations of 2 tuples : " + str(res))
#This code is contributed by Jyothi pinjala.
 
 
Output
The original tuple 1 : (4, 5) The original tuple 2 : (7, 8) All pair combinations of 2 tuples : [(4, 7), (4, 8), (5, 7), (5, 8), (7, 4), (7, 5), (8, 4), (8, 5)]

Time complexity: O(nm)
The time complexity of this algorithm is O(nm) because it uses two nested loops to iterate through all pairs of elements in the two input tuples, which takes n*m iterations where n and m are the lengths of the input tuples.

Auxiliary Space: O(nm)
The space complexity of this algorithm is also O(nm) because a new list is created to store the result, and the size of the list is proportional to the number of pairs generated.

METHOD 4:Using nested loops

APPROACH:

The above program generates all possible pairs of elements from two given tuples, and stores them in a filtered list. The filtered list includes both the tuples with the first element from the first tuple and the second element from the second tuple, and the tuples with the first element from the second tuple and the second element from the first tuple.

ALGORITHM:

1.Initialize an empty list to store the filtered tuples.
2.Use nested loops to iterate over each element in tuple 1 and tuple 2.
3.Append a tuple of the two elements to the filtered list.
4.Append a tuple of the two elements in reverse order to the filtered list.
5.Output the filtered list.

Python3




# input
tuple1 = (4, 5)
tuple2 = (7, 8)
 
# initialize an empty list to store the filtered tuples
filtered_tuples = []
 
# iterate over each element in tuple 1
for element1 in tuple1:
    # iterate over each element in tuple 2
    for element2 in tuple2:
        # append a tuple of the two elements to the filtered list
        filtered_tuples.append((element1, element2))
        # append a tuple of the two elements in reverse order to the filtered list
        filtered_tuples.append((element2, element1))
 
# output
print(filtered_tuples)
 
 
Output
[(4, 7), (7, 4), (4, 8), (8, 4), (5, 7), (7, 5), (5, 8), (8, 5)] 

Time complexity: The time complexity of this program is O(n^2), where n is the length of the tuples. This is because the program uses nested loops to iterate over each element in the two tuples.

Space complexity: The space complexity of this program is O(n^2), as the filtered list will contain all possible pairs of elements from the two tuples. The exact space complexity will depend on the length of the tuples.



Next Article
Print a List of Tuples in Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python List-of-Tuples
  • Python tuple-programs
Practice Tags :
  • python

Similar Reads

  • Python | All possible N combination tuples
    Sometimes, while working with Python tuples, we might have a problem in which we need to generate all possible combination pairs till N. This can have application in mathematics domain. Let's discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + product() T
    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
  • Print a List of Tuples in Python
    The task of printing a list of tuples in Python involves displaying the elements of a list where each item is a tuple. A tuple is an ordered collection of elements enclosed in parentheses ( ), while a list is an ordered collection enclosed in square brackets [ ]. Using print()print() function is the
    2 min read
  • Python | Addition of tuples
    Sometimes, while working with records, we might have a common problem of adding contents of one tuple with the corresponding index of other tuple. This has application in almost all the domains in which we work with tuple records. Let's discuss certain ways in which this task can be performed. Metho
    5 min read
  • Python - Pairwise Addition in Tuples
    Sometimes, while working with data, we can have a problem in which we need to find cumulative result. This can be of any type, product or summation. Here we are gonna discuss about adjacent element addition. Let’s discuss certain ways in which this task can be performed. Method #1 : Using zip() + ge
    4 min read
  • Python - All replacement combination from other list
    Given a list, the task is to write a Python program to perform all possible replacements from other lists to the current list. Input : test_list = [4, 1, 5], repl_list = [8, 10] Output : [(4, 1, 5), (4, 1, 8), (4, 1, 10), (4, 5, 8), (4, 5, 10), (4, 8, 10), (1, 5, 8), (1, 5, 10), (1, 8, 10), (5, 8, 1
    3 min read
  • Python program to get all unique combinations of two Lists
    The goal is to combine each item from first list with each item from second list in every possible unique way. If we want to get all possible combinations from two lists. Python’s itertools library has a function called a product that makes it easy to generate combinations of items from multiple lis
    2 min read
  • Python | Pair Product combinations
    Sometimes, while working with data, we can have a problem in which we need to perform tuple multiplication among all the tuples in list. This can have application in many domains. Let’s discuss certain ways in which this task can be performed. Method #1 : Using combinations() + list comprehension Th
    4 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
    10 min read
  • Python - All combination Dictionary List
    Given 2 lists, form all possible combination of dictionaries that can be formed by taking keys from list1 and values from list2. Input : test_list1 = ["Gfg", "is", "Best"], test_list2 = [4] Output : [{'Gfg': 4, 'is': 4, 'Best': 4}]Explanation : All combinations dictionary list extracted. Input : tes
    3 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