Suppose that in Python I have 3 lists: a, b, c
of variable lengths. For example :
a=[1,2,3]
b=[4,5,6]
c=[7,8]
I would like to get every unique combination of TWO elements of the 3 lists above, i. e.
[1,4],[1,5],[1,6],[1,7],[1,8],[2,4],[2,5]...
and NOT unique combinations of the 3 lists (such as [1,4,7],[1,4,8],...
).
I have looked at the solution here using itertools
that is perfectly fine for 2 lists ; however, this solution does not work anymore when including a n
th list because the unique combinations are of length n
.
Here is what I have tried:
import itertools
a=[1,2,3]
b=[4,5,6]
c=[7,8]
d=list(itertools.product(a,b,c))
[(1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (1, 6, 7), (1, 6, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (2, 6, 7), (2, 6, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8), (3, 6, 7), (3, 6, 8)]
Note: Above is just an example and the solution should work for n
lists of variable length and with possibly the same value being in different lists... Any idea of how I could do would be greatly appreciated! :)
EDIT: as asked by @SirParselot, the elements have to come from different lists
import itertools as it
at the top of the script. I'll add some code to my answer.