Python All pair combinations of 2 tuples (original) (raw)

When working with Python tuples, you might need to generate all possible pair combinations between two tuples. This operation is useful in areas such as data science, simulation, and game development.

**Example:

**Input : t1 = (7, 2), t2 = (7, 8)
**Output : [(7, 7), (7, 8), (2, 7), (2, 8), (7, 7), (7, 2), (8, 7), (8, 2)]

Let's discuss certain ways in which this task can be performed.

The combination of itertools.product() and itertools.chain() is the most concise and efficient approach to generate all pair combinations.

from itertools import chain, product

t1 = (4, 5) t2 = (7, 8)

res = list(chain(product(t1, t2),product(t2, t1))) print(str(res))

`

Output

[(4, 7), (4, 8), (5, 7), (5, 8), (7, 4), (7, 5), (8, 4), (8, 5)]

**Explanation:

Using List Comprehension

List comprehension provides a concise and readable way to perform the same task. It iterates over all elements of both tuples, combining them into pairs.

Python `

t1 = (4, 5) t2 = (7, 8)

res = [(a, b) for a in t1 for b in t2] +
[(a, b) for a in t2 for b in t1]

print(str(res))

`

Output

[(4, 7), (4, 8), (5, 7), (5, 8), (7, 4), (7, 5), (8, 4), (8, 5)]

**Explanation:

This method manually uses nested list comprehensions to generate all combinations.

Python `

import itertools

t1 = (4, 5) t2 = (7, 8)

res = [(a, b) for a in t1 for b in t2] +
[(a, b) for a in t2 for b in t1]

print(str(res))

`

Output

[(4, 7), (4, 8), (5, 7), (5, 8), (7, 4), (7, 5), (8, 4), (8, 5)]

**Explanation:

Using Nested Loops

This approach uses simple for loops to create all possible forward and reverse pair combinations.

Python `

t1 = (4, 5) t2 = (7, 8) res = []

for ele1 in t1: for ele2 in t2: res.append((ele1, ele2)) res.append((ele2, ele1))

print(res)

`

Output

[(4, 7), (7, 4), (4, 8), (8, 4), (5, 7), (7, 5), (5, 8), (8, 5)]

**Explanation: