I would like to create a tuple which present all the possible pairs from two tuples
this is example for what I would like to receive :
first_tuple = (1, 2) second_tuple = (4, 5) mult_tuple(first_tuple, second_tuple)
output :
((1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2))
This is what I did which succeed however look a bit cumbersome :
def mult_tuple(tuple1, tuple2): ls=[] for t1 in tuple1: for t2 in tuple2: c=(t1,t2) d=(t2,t1) ls.append(c) ls.append(d) return tuple(ls) first_tuple = (1, 2) second_tuple = (4, 5) mult_tuple(first_tuple, second_tuple)
The code I wrote works , however I am looking for a nicer code
thank you in advance
In C#, a 2-tuple is a tuple that contains two elements and it is also known as pair. You can create a 2-tuple using two different ways: Using Tuple<T1,T2>(T1, T2) Constructor. Using the Create method.
Creating a Tuple A tuple in Python can be created by enclosing all the comma-separated elements inside the parenthesis (). Elements of the tuple are immutable and ordered. It allows duplicate values and can have any number of elements.
Care has to be taken while pairing the last element with the first one to form a cyclic pair. zip function can be used to extract pairs over the list and slicing can be used to successively pair the current element with the next one for the efficient pairing.
You can, however, concatenate 2 or more tuples to form a new tuple. This is because tuples cannot be modified.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With