63

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

SilentGhost
  • 287,765
  • 61
  • 300
  • 288
Ian Davis
  • 1,139
  • 1
  • 8
  • 8

3 Answers3

110

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')]
John La Rooy
  • 281,034
  • 50
  • 354
  • 495
7

You can do it with a multi-level list comprehension:

>>> L1=['a','b','c']
>>> L2=['d']
>>> L3=['e','f']
>>> [[i,j,k] for i in L1 for j in L2 for k in L3]
[['a', 'd', 'e'], ['a', 'd', 'f'], ['b', 'd', 'e'], ['b', 'd', 'f'], ['c', 'd', 'e'], ['c', 'd', 'f']]
Daniel DiPaolo
  • 53,439
  • 13
  • 112
  • 113
  • 4
    This requires you to know in advance the number of `n` (`n = 3` in your answer) :) – badp May 17 '10 at 22:10
  • Thanks, but I don't know the number of lists in advance. I have the equivalent of [L1, L2, L3, ...] – Ian Davis May 17 '10 at 22:10
  • Ah okay I was unclear on what you meant by "knowing the number of arguments in advance" - I thought you may have meant the lengths of the lists – Daniel DiPaolo May 17 '10 at 22:12
6

itertools.product works for me.

>>> l=[ [ 1, 2, 3], [4], [5, 6] ]
>>> list(itertools.product(*l))
[(1, 4, 5), (1, 4, 6), (2, 4, 5), (2, 4, 6), (3, 4, 5), (3, 4, 6)]
>>> l=[ [ 1, 2, 3], [4], [5, 6],[7,8] ]
>>> list(itertools.product(*l))
[(1, 4, 5, 7), (1, 4, 5, 8), (1, 4, 6, 7), (1, 4, 6, 8), (2, 4, 5, 7), (2, 4, 5, 8), (2, 4, 6, 7), (2, 4, 6, 8), (3, 4, 5, 7), (3, 4, 5, 8), (3, 4, 6,
 7), (3, 4, 6, 8)]
>>>
Wai Yip Tung
  • 17,176
  • 9
  • 41
  • 46