Q:

Python program to print all pair combinations of elements from 2 tuples

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Now, let's get back to our topic where we will pair combinations of tuples.

Printing all pair combinations of elements from 2 tuples

We will be traversing each of the tuples and combining them to form a list of pairs. In python, we have multiple ways, direct methods, and built-in methods to create and print pairs.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to find pair combinations of elements is by using list comprehension to perform index combinations and store the pair tuples in a list.

# Python program to print all pair combinations 
# of elements from 2 tuples

# Creating and printing initial tuples 
myTuple1 = (2, 7)
myTuple2 = (5, 9)
print("Elements of tuple 1 are " + str(myTuple1))
print("Elements of tuple 2 are " + str(myTuple2))

# All pair combinations of 2 tuples
# Using list comprehension
pairList = [(a, b) for a in myTuple1 for b in myTuple2]
pairList = pairList + [(b, a) for a in myTuple1 for b in myTuple2]

# Printing combination list 
print("All pair combination list is " + str(pairList))

Output:

Elements of tuple 1 are (2, 7)
Elements of tuple 2 are (5, 9)
All pair combination list is [(2, 5), (2, 9), (7, 5), (7, 9), (5, 2), (9, 2), (5, 7), (9, 7)]

Method 2:

An Alternative method to print pair combinations is using some built-in method in the Python's itertools library. We will be using the product() method to pair tuple elements. For both the tuples and chain them to print the final result as a list.

# Python program to print all pair combinations
# of elements from 2 tuples

from itertools import chain, product

# Creating and printing initial tuples 
myTuple1 = (2, 7)
myTuple2 = (5, 9)
print("Elements of tuple 1 are " + str(myTuple1))
print("Elements of tuple 2 are " + str(myTuple2))

# All pair combinations of 2 tuples
# Using list comprehension
pairList = list(chain(product(myTuple1, myTuple2), product(myTuple2, myTuple1)))

# Printing combination list 
print("All pair combination list is " + str(pairList))

Output:

Elements of tuple 1 are (2, 7)
Elements of tuple 2 are (5, 9)
All pair combination list is [(2, 5), (2, 9), (7, 5), (7, 9), (5, 2), (5, 7), (9, 2), (9, 7)]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now