Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get all tuple permutations between two lists

Given two lists of length n, I’ve been trying to find a pythonic way to return a list of a list of n-tuples where each list of tuples is a distinct permutation of the possible values between the two lists. So given:

a = [1, 2]
b = [3, 4]

I’d expect an output of:

[ [(1, 3), (2, 4)], [(1, 4), (2, 3)] ]

I looked at questions like permutations of two lists in python, but that’s not quite what I’m after. I looked at the itertools library and nothing immediately popped out at me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What’s a good pythonic way to solve this?

>Solution :

You could do it that way

[list(zip(x,b)) for x in itertools.permutations(a)]

What you really want is, after all, permutations of one of the list, and all possible matching. So it is more a permutations problem than a product problem. So here, I choose to keep b as is, and try all possible orders for a, and zip those permutations of a with b

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading