Program to find all pair combinations of two tuples using Python

Introduction

The task is to find and print all possible combination of digits form two tuples. 

Program to find all pair combinations of two tuples using Python

Program

Approach1

from itertools import chain, product
ip_tuple1 = (1, 2)
ip_tuple2 = (3, 4)
print("The given two tuples are : "+str(ip_tuple1) + "and" + str(ip_tuple2))
# Using chain( and product()
output = list(chain(product(ip_tuple1, ip_tuple2), product(ip_tuple2, ip_tuple1)))
print("Output list : "+str(output))

Output:

Program to find all pair combinations of two tuples using Python Output 1

Approach 2

from itertools import chain, product
ip_tuple1 = (1, 2)
ip_tuple2 = (3, 4)
print("The given two tuples are : "+str(ip_tuple1) + "and" + str(ip_tuple2))
# Using list comprehension
output = [(x, y) for x in ip_tuple1 for y in ip_tuple2]
output = output + [(x, y) for x in ip_tuple2 for y in ip_tuple1]
print("Output list : "+str(output))

Output:

Program to find all pair combinations of two tuples using Python Output 2

Explanation

In first approach, we have used product() and chain() functions to find all the combinations of digits. The product function is used to find the pair combinations and chain() function is used to combine the output.

In our second approach, we have paired one index digits using list comprehension and then created another pair combination other index. Both the output are combined and printed on the screen.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.