Search code examples
pythonalgorithmpermutation

Python generate all n-permutations of n lists


I have n lists of different lengths of which I want to create all possible permutations.

so e.g. if a=[1,2] and b=[3,4,5] then I would love to obtain res=[[1,3],[1,4],[1,5],[2,3],[2,4],[2,5]] I've been trying to achieve this using a recursive function, which turned out to be neither very efficient nor very pythonic. How would an experienced Python programmer tackle the problem?


Solution

  • It's called the Cartesian product of two sequences.

    This is already available in Python as a library function: itertools.product.

    Example:

    >>> import itertools
    >>> a = [1, 2]
    >>> b = [3, 4, 5]
    >>> list(itertools.product(a, b))
    [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]