create a tuple from pairs

itertools.product gives you what you want. However, since the Cartesian product of two tuples is not commutative (product(x,y) != product(y,x)), you need to compute both and concatenate the results.

>>> from itertools import chain, product
>>> x = (1,4)
>>> y = (2, 5)
>>> list(chain(product(x,y), product(y,x)))
[(1, 2), (1, 5), (4, 2), (4, 5), (2, 1), (2, 4), (5, 1), (5, 4)]

(You can use chain here instead of permutations because there are only two permutations of a 2-tuple, which are easy enough to specify explicitly.)


Here is an ugly one-liner.

first_tuple = (1, 2)
second_tuple = (4, 5)
tups = [first_tuple, second_tuple]
res = [(i, j) for x in tups for y in tups for i in x for j in y if x is not y]
# [(1, 4), (1, 5), (2, 4), (2, 5), (4, 1), (4, 2), (5, 1), (5, 2)]

Unless you are using this for sport, you should probably go with a more readable solution, e.g. one by MrGeek below.


You can use itertools's product and permutations:

from itertools import product, permutations

first_tuple, second_tuple = (1, 2), (4, 5)

result = ()

for tup in product(first_tuple, second_tuple):
    result += (*permutations(tup),)

print(result)

Output:

((1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2))

product produces the tuples (two elements) produced equally by the nested for loop structure (your t1 and t2 variables), and permutations produces the two permutations produced equally by your c and d variables.

Tags:

Python

Tuples