All possible permutations of a set of lists in Python

Ian Davis picture Ian Davis · May 18, 2010 · Viewed 24.4k times · Source

In Python I have a list of n lists, each with a variable number of elements. How can I create a single list containing all the possible permutations:

For example

[ [ a, b, c], [d], [e, f] ]

I want

[ [a, d, e] , [a, d, f], [b, d, e], [b, d, f], [c, d, e], [c, d, f] ]

Note I don't know n in advance. I thought itertools.product would be the right approach but it requires me to know the number of arguments in advance

Answer

John La Rooy picture John La Rooy · May 18, 2010

You don't need to know n in advance to use itertools.product

>>> import itertools
>>> s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ]
>>> list(itertools.product(*s))
[('a', 'd', 'e'), ('a', 'd', 'f'), ('b', 'd', 'e'), ('b', 'd', 'f'), ('c', 'd', 'e'), ('c', 'd', 'f')]