How to get permutations between two lists of unequal length with Python?

Sometimes, we want to to get permutations between two lists of unequal length with Python.

In this article, we’ll look at how to get permutations between two lists of unequal length with Python.

How to get permutations between two lists of unequal length with Python?

To get permutations between two lists of unequal length with Python, we can use the itertools.product method.

For instance, we write:

import itertools
from pprint import pprint

inputdata = [
    ['a', 'b', 'c'],
    ['d'],
    ['e', 'f'],
]
result = list(itertools.product(*inputdata))
pprint(result)

We call itertools.product with the lists unpacked from inputdata.

Then we call list on the returned iterable to convert it to a list and assign the returned list to result.

Therefore, result is:

[('a', 'd', 'e'),
 ('a', 'd', 'f'),
 ('b', 'd', 'e'),
 ('b', 'd', 'f'),
 ('c', 'd', 'e'),
 ('c', 'd', 'f')]

Conclusion

To get permutations between two lists of unequal length with Python, we can use the itertools.product method.