Search code examples
pythoncombinationspermutationpython-itertools

Python itertools get permutations and combinations of a list of lists


My brain is going to explode as I try to figure how to get all permutations and combinations of a list of lists in Python. The problem is to write a function which would for the following input list [['I1', 'I2', 'I3'], ['I2', 'I3']] return the following:

[['I1', 'I2', 'I3'], ['I2', 'I3']]
[['I1', 'I3', 'I2'], ['I2', 'I3']]
[['I2', 'I1', 'I3'], ['I2', 'I3']]
[['I2', 'I3', 'I1'], ['I2', 'I3']]
[['I3', 'I1', 'I2'], ['I2', 'I3']]
[['I3', 'I2', 'I1'], ['I2', 'I3']]
[['I1', 'I2', 'I3'], ['I3', 'I2']]
[['I1', 'I3', 'I2'], ['I3', 'I2']]
[['I2', 'I1', 'I3'], ['I3', 'I2']]
[['I2', 'I3', 'I1'], ['I3', 'I2']]
[['I3', 'I1', 'I2'], ['I3', 'I2']]
[['I3', 'I2', 'I1'], ['I3', 'I2']]
[['I2', 'I3'], ['I1', 'I2', 'I3']]
[['I2', 'I3'], ['I1', 'I3', 'I2']]
[['I2', 'I3'], ['I2', 'I1', 'I3']]
[['I2', 'I3'], ['I2', 'I3', 'I1']]
[['I2', 'I3'], ['I3', 'I1', 'I2']]
[['I2', 'I3'], ['I3', 'I2', 'I1']]
[['I3', 'I2'], ['I1', 'I2', 'I3']]
[['I3', 'I2'], ['I1', 'I3', 'I2']]
[['I3', 'I2'], ['I2', 'I1', 'I3']]
[['I3', 'I2'], ['I2', 'I3', 'I1']]
[['I3', 'I2'], ['I3', 'I1', 'I2']]
[['I3', 'I2'], ['I3', 'I2', 'I1']]

Any ideas how to make it efficiently in Python? Thanks!

P.S. The function should return all permutations and combinations for input list of lists of any size, not just the two-element list shown above


Solution

  • As a full functional approach you can use permutations() and product() and chain() functions from itertools module and built in function map():

    >>> from itertools import permutations, product, chain
    >>> def my_prod(lst):
    ...     return product(*map(permutations, lst))
    ... 
    >>> 
    >>> list(chain(*map(my_prod, permutations(lst))))
    [(('I1', 'I2', 'I3'), ('I2', 'I3')), (('I1', 'I2', 'I3'), ('I3', 'I2')), (('I1', 'I3', 'I2'), ('I2', 'I3')), (('I1', 'I3', 'I2'), ('I3', 'I2')), (('I2', 'I1', 'I3'), ('I2', 'I3')), (('I2', 'I1', 'I3'), ('I3', 'I2')), (('I2', 'I3', 'I1'), ('I2', 'I3')), (('I2', 'I3', 'I1'), ('I3', 'I2')), (('I3', 'I1', 'I2'), ('I2', 'I3')), (('I3', 'I1', 'I2'), ('I3', 'I2')), (('I3', 'I2', 'I1'), ('I2', 'I3')), (('I3', 'I2', 'I1'), ('I3', 'I2')), (('I2', 'I3'), ('I1', 'I2', 'I3')), (('I2', 'I3'), ('I1', 'I3', 'I2')), (('I2', 'I3'), ('I2', 'I1', 'I3')), (('I2', 'I3'), ('I2', 'I3', 'I1')), (('I2', 'I3'), ('I3', 'I1', 'I2')), (('I2', 'I3'), ('I3', 'I2', 'I1')), (('I3', 'I2'), ('I1', 'I2', 'I3')), (('I3', 'I2'), ('I1', 'I3', 'I2')), (('I3', 'I2'), ('I2', 'I1', 'I3')), (('I3', 'I2'), ('I2', 'I3', 'I1')), (('I3', 'I2'), ('I3', 'I1', 'I2')), (('I3', 'I2'), ('I3', 'I2', 'I1'))]
    

    Here the map function maps the permutations on your sub lists and then product will create the products of permutations.

    As another way (and slightly faster) you can use a list comprehension instead of map():

    >>> def my_prod(lst):
    ...     return product(*[permutations(sub) for sub in  lst])