from itertools import chain,product
first_tuple = (1, 2)
second_tuple = (4, 5)
combined = list(chain(*[[(f,s),(s,f)] for f in first_tuple for s in second_tuple]))
print (combined)
output:
[(1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2)]
.
itertools.product()
This tool computes the cartesian product of input iterables. It is
equivalent to nested for-loops. For example, product(A, B) returns
the same as ((x,y) for x in A for y in B).
To get first part of desired list is:
list(product(first_tuple, second_tuple)) # (1, 4), (4, 1), (1, 5), (5, 1)
for the second part is enough to reverse:
list(product(second_tuple, first_tuple)) # (2, 4), (4, 2), (2, 5), (5, 2)
.
combined1 = list(product(first_tuple, second_tuple)) + list(product(second_tuple, first_tuple))
print (combined1)
output:
[(1, 4), (1, 5), (2, 4), (2, 5), (4, 1), (4, 2), (5, 1), (5, 2)]